As you can see in the second example, you can leave the implementation for the property. Then, .NET will automatically create a local variable for the property and implement simple retrieval and configuration.
public int MyProperty { get; private set; }
virtually equivalent
private int _myProperty; public int MyProperty { get { return _myProperty; } private set { _myProperty = value; } }
Record
public int MyProperty { get; }
does not work at all, since the automatic properties must be implemented by the receiver and setter, and
public int MyProperty { get; private set; }
provides you with a property that can return any int , but can only be changed in the current class.
public int MyProperty { get { ... } }
Creates a read-only property.
Question: what do you need? If you already have a member variable that is used in your class, and you only want to return the current value using the property, you will do fine with
public int MyProperty { get { return ...; }}
However, if you want a read-only property that needs to be set inside your code (but not from other classes) without explicitly declaring a member variable, you need to go with the private set approach.
source share