Why use private property setting tools, 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 a property here, when we can set _myFieldinside the class as needed? Why do we want to use the installer MyProperty?

+5
source share
6 answers

The installer may implement different behavior / logic when updating the property, so you do not need to manually implement it in every place where the property can be updated.

He can:

  • automatically update other fields
  • Confirm the new value (for example, make sure the email address matches the regular expression)
  • , ,

:

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;
    }
}
+7

(get set) , , . , . , .

: ? , . , . , . .

+5

, , , . - ( ) . ( , , ) ( , , ). , , .

+3

setter , , int, , .

public int MyProp 
{
    get { return _my_prop;}
    private set {
        if value > 10 {
            _my_prop = 10;
        }

    }
}
+2

2 :

  • , , .

, ,

+1

you need a private setter in a property in order to use your field wrapped in a property only to directly change another function, the properties of your class. Thus, in one place (property) you set the value of your field, but all other elements of your class do not have direct access to your private field, but through a property that completes it.

+1
source

All Articles