c# – Quick Question About Get and Set – Education Career Blog

If there is the following code in a class, are get and set methods associated to the variable? How can I access get and set with an instance of the class?

public string Something { get; set; }

,

This is essentially a compiler trick. When you compile the code the compiler will generate a hidden field and the necessary code to return and set the field in the get and set.

You would access this property just like you would access any other property. MyClass.Something = "bla".

,

This syntax comes with .Net Framework 3.5 (automatic-property)

It’s like :

private string something;
public string Something
{
     get { return something; }
     set { something = value; }
}

To access to this variable (supposed to be in a MyClass class) :

// GET
    MyClass myObj = new MyClass();
    string test = myObj.Something;
// SET
    myObj.Something = "blabla";

,

This is an auto-property, which creates a backing field in the compiler, which you don’t need to write code for.

get:

var str = instance.Something;

set:

instance.Something = "new value";

,

  1. It’s a new feature of compiler
  2. It’s called Automatic Properties
  3. You don’t need to define a backing store for automatic properties, the compiler does that job for you.
  4. You can not inject custom code in automatic properties, you need to revert back to normal 1.1 style of declaring properties.
  5. You can access automatic properties as you access normal properties

,

A backing variable complete with getter and setter methods(*) are created for you by the compiler, but you would not see them in your standard code. You would simply access the property directly.

myClass.Something = "blah"; // uses set
string myValue = myClass.Something; // uses get;

*These methods are created for properties rather they are auto-implemented or not. The compiler-generated backing variable is added to the mix in the case of an auto-implemented property.

,

This is like the code below, but many fewer keystrokes 🙂

public string Something {
    get() {
        return _Something;
    }
    set(string value) {
        _Something = value;
    }
}

,

The compiler turns this:

public string Something { get; set; } 

Into something like this (in IL, converted to C# for your convenience):

string _something;
public string get_Something() { return _something; }
public void set_Something(string value) { _something = value; } 

Also, the compiler turns these lines:

Something = "test";
var result = Something;

Into this:

set_Something("test");
var result = get_Something();

So you see, it’s all method calls underneath (just like in Java), but it’s really sweet to have the property syntax in C#. But if you try to call these methods directly, you get an error.

Leave a Comment