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; }
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 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";
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;
}
}
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";
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.