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

Setting a default value for C# Auto-implemented properties

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

C# Property Vs Field

  1. There are some attributes that you can add to a property that you can't add to a field.
  2. Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.
  3. You can't databind to a field whereas you can to a property.
  4. If you start off using a field, you can't later (easily) change them to a property.
  5. Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface).
Prev
Index Page
Next
©Net-informations.com