Automatic properties are supported by C# since version 3.0. These properties are used when no additional logic is required in the
text property accessors. These are used to make it easier to have
text private variables in the class, but allow them to be visible to outside the class (without being able to modify them)
The declaration would look something like this:
public string Name { get; set; }
It is a property that has backing field generated by compiler. The
text C# compiler creates private fields correspond to the properties and are accessible using the
text get and set methods. They are just syntactic sugar so you won't need to write the following more lengthy code:
public class Color
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
Read-only auto-property
As of C# 6.0 or later, you can also create true
text readonly properties. That means,
text immutable properties that cannot be changed outside of the constructor:
public string SomeProperty { get; }
public MyClass() { this.SomeProperty = "myProperty"; }
At compile time that will become:
readonly string pName;
public string SomeProperty { get { return this.pName; } }
public MyClass() { this.pName = "myProperty"; }
In
text immutable classes with a lot of members this saves a lot of excess code.
Assigning value to
text auto-property means assigning value to backing field. So if you wanted to create a field where it was only settable
text inside the class, you could do:
public string Prop { get; private set; }
This is same as:
private string name;
public string Prop
{
get { return name; }
private set { name = value; }
}