Reputation: 25
I just wanted to check if I understand correctly. The return value in get make the return value equal the private instance data. And the set value makes the value of the public value equal to the value of the private instance. Do I understand this correctly?
Upvotes: 1
Views: 281
Reputation: 100620
Not always.
Get
returns whatever developer thinks value of a property should be and set
changes whatever the developer finds suitable to store the data. Often there is one-to-one mapping between property and internal field, but not always.
int UltimateAnswer {get {return 42;}} // no internal field at all
int Direct
{
get {return _direct;}
set {_direct = value;}
}
int WithConversion
{
get {return _stored * 100;}
set { _stored = value / 100;}
}
int AutoFiled {get;set;} // this one directly maps to automatically created field.
Upvotes: 5
Reputation: 223402
If you are property is defined as:
private int _value;
public int Value
{
get { return _value; }
set { _value = value; }
}
Then yes, get is returning the value of the private field _value
and set is setting up the _value
but it could be different as well.
public int Value
{
get { return getCalculatedValue() }
set {
if (_value > 0)
{
_value = value;
}
else
{
_value = -1;
}
}
}
In the above example, get is returning you the calculatedValue from some function named getCalculatedValue()
and set is validating the value for some condition and then setting it appropriately.
Upvotes: 4