An auto-property is a short designation for an automatically-implemented property , where the developer does not need to explicitly declare a support field, and the compiler sets it up behind him.
1. Auto-property with a private network device
public class Context1 { public Context1() { this.Items = new List<string>(); } public List<string> Items { get; private set; } }
Auto properties can have different capabilities for setter and getter, specifying more restrictive accessibility for access, for which accessibility is different from accessibility of properties.
Other examples:
public string Prop1 { get; private set; } public string Prop2 { get; protected set; } public string Prop3 { get; internal set; } public string Prop4 { protected internal get; set; }
Access to these accessories with different availability can be obtained anywhere available for this availability, and not just from the designer.
2. Read-only property with support field
public class Context2 {private readonly List of elements;
public Context2() { this.items = new List<string>(); } public List<string> Items { get { return this.items; } }
} Before C # 6, the only way to set the value of a read-only property was to explicitly declare a support field and set it directly.
Since the field has a readonly accessory, it can only be installed when building an object.
3. Auto-read-only property
public class Context3 { public List<string> Items { get; } = new List<string>(); }
Starting with C # 6 , §2 can be processed by the compiler if it has a support field similar to read-write auto-negotiation, but in this case the support field can only be set when building an object.
4. Auto-read-only property with godter getter expression
public class Context4 { public List<string> Items => new List<string>(); }
When properties have a value that changes each time it receives, C # 6 allows you to declare a receiver body using lambda-type syntax.
The above code is equivalent to this:
public class Context4 { public List<string> Items { get { return new List<string>(); } } }