In C#, we can do something like:
private string _myField;
public string MyProperty
{
get { return _myField; }
private set { _myField = value; }
}
What is the advantage of using a private setter in the property here while we can set _myField
inside the class as we want? Why would we want to use the setter of MyProperty
?
A setter can implement other behaviour/logic when a property is updated, so that you don't have to manually implement it at every location where a property might be updated.
It can:
For example:
private string _myField;
private int _myField_num_updated;
private DateTime _myField_updated_at;
public string MyProperty
{
get { return _myField; }
private set {
_myField = value;
_myField_num_updated++;
_myField_updated_at = DateTime.Now;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With