What's New in Visual Basic 14: ReadOnly Auto-Implemented Properties
In Visual Basic 14, can now have read-only auto-implemented properties: Just add the ReadOnly keyword to the Property declaration. Here's an example:
Public ReadOnly Property Id As String
You can set the property by name from within your class' constructors. This example sets my Customer's Id property:
Sub New(Id As String)
Me.Id = Id
From elsewhere in your class, you can not set the property's value using the property's name. This code won't work anywhere outside of the class' constructor:
Me.Id = Id
However, you can access the backing field for the property and set the property's value through that. The backing field will have the same name as the property with an underscore prefixed to the property name.
This example updates my read-only Id property through its backing field:
_Id = "Fred"
On a related note: If you have an interface that specifies that a property is read-only, in Visual Basic 14 you don't have to honor that restriction when you implement the interface in a class. The interface that specifies a ReadOnly property will be happy with either a read-only or a read-write implementation in the class that implements the interface.
Posted by Peter Vogel on 05/29/2015 at 11:01 AM