Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use private property setters since member variables can be accessed directly?

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?

like image 827
hattenn Avatar asked Aug 18 '12 00:08

hattenn


1 Answers

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:

  • automatically update other fields
  • Validate the new value (eg. ensure an email address matches a regular expression)
  • To keep code that needs to be run every time a field is updated in one place

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;
    }
}
like image 124
ronalchn Avatar answered Sep 20 '22 10:09

ronalchn