Auto properties have been a great addition to .NET development. They simplify the old method of coding properties using a local variable and a full implementation of get
and set
. See “Creating an Automatically Implemented Property” in the later section “Language Features.”
However, up until 2015, auto properties required both a getter and a setter; this makes it hard to use them with immutable data types. The latest release now allows you to create auto properties as read only (with just the get
). A read-only backing field is created behind the scenes on your behalf. The following shows an example of a full property, a standard auto property, and the new read-only auto property.
C#
Public class Employee
{
//full property
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
//standard auto property
public string Address { get; set; }
//read-only auto property
public string EmpId { get; }
}
Public Class Employee
'full property
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
'standard auto property
Public Property Address As String
'read-only auto property
Public ReadOnly Property EmpId As String
End Class
Read-only auto properties can be assigned from the constructor. Again, they have a hidden backing field. The compiler knows this field exists and thus allows this assignment. The following shows a constructor inside the Employee
class shown above assigning the read-only EmpId
property. Notice that, in Visual Basic, the Sub New constructor must be used to assign a read-only property.
C#
public Employee(string id)
{
EmpId = id;
}
VB
Public Sub New(ByVal id As String)
EmpId = id
End Sub
You can also initiate read-only auto properties at the time of their creation (just like the field that backs them), as shown next. Note that if you were to combine this assignment with the previous constructor code (that initialized the read only property), the object creation would happen first. Thus, the constructor init would take precedence.
public string EmpId { get; } = "NOT ASSIGNED";
VB
Public ReadOnly Property EmpId As String = "NOT ASSIGNED"