Auto-Implemented Properties
Posted
Sun, Apr 11 2010 18:21
by
Deborah Kurata
One of the new features in VB 10.0 is auto-implemented properties. Auto-implemented properties are a shorter syntax for your property statements that automatically implement a backing field so you don't have to manually define one.
(C# has had auto-implemented properties since C# 3.0. The examples here show both C# and VB for completeness.)
In this example, the Customer class has four properties as shown below.
In VB:
Public Class Customer
Public Property CustomerId As Integer
Public Property FirstName() As String
Public Property LastName() As String
Public Property EmailAddress() As String
End Class
In C#:
public class Customer
{
public int CustomerId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string EmailAddress { get; set; }
}
Without auto-implemented properties, the code is MUCH longer. The code shown above is functionally equivalent to the following:
In VB:
Public Class Customer
Private _CustomerId As Integer
Public Property CustomerId() As Integer
Get
Return _CustomerId
End Get
Set(ByVal value As Integer)
_CustomerId = value
End Set
End Property
Private _FirstName As String
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Private _LastName As String
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Private _EmailAddress As String
Public Property EmailAddress () As String
Get
Return _EmailAddress
End Get
Set(ByVal value As String)
_EmailAddress = value
End Set
End Property
End Class
In C#:
public class Customer
{
private int _CustomerId;
public int CustomerId
{
get { return _CustomerId; }
set { _CustomerId = value; }
}
private string _FirstName;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _LastName;
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _EmailAddress;
public string EmailAddress
{
get { return _EmailAddress; }
set { _EmailAddress = value; }
}
}
Use auto-implemented properties whenever you need to define a property that does not require specialized code in the getter or setter.
Enjoy!
NOTE: For more information on the features and limitations of auto-implemented properties, see Auto-Implemented Properties Part II.