Auto-Implemented Properties Part II
Posted
Thu, Aug 12 2010 22:51
by
Deborah Kurata
This prior post covered the basics of auto-implemented properties in C# and VB. This current post takes a closer look at some of the features of the auto-implemented properties and how they are different between VB and C#.
C# auto-implemented properties have the following features:
- Getters and setters can have different access levels.
- Snippets are available for both the expanded property syntax (propfull) and for the auto-implemented property syntax (prop).
VB.NET auto-implemented properties have the following features:
- Properties can have a default value.
- Visual Studio automatically defines a backing field that you can access.
- Auto-implemented properties can be expanded.
First, the C# code:
public int CustomerId { get; internal set; }
Since the syntax defines the get and set, you can add separate assessors for the get or set as necessary.
The VB.NET code:
Public Property PurchaseDate As DateTime = DateTime.Now();
The code above sets a default value for the PurchaseDate property using the auto-implemented syntax.
Public Property CustomerId As Integer
Public Sub New(ByVal newCustomerId As Integer)
_CustomerId = newCustomerId
End Sub
With VB, Visual Studio defines a hidden backing variable that is named with the same name as the property with an underscore prefix. So the CustomerId property has a hidden variable named _CustomerId. You can access this backing variable as shown above.
If you originally used an auto-implemented property and then determine that you want an expanded property, you can expand an auto-implemented property in VB.
In the line directly below the auto-implemented property statement, type in G<Enter>
After pressing the <Enter> key, the result is shown below:
Use these features as needed when you use auto-implemented properties.
Enjoy!