.NET Tips and Tricks

Blog archive

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:

Class Customer
   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
End Sub

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


comments powered by Disqus

Featured

  • Microsoft Eases Integration with Semantic Kernel AI SDK

    The basic idea is to provide unified API abstractions, especially for idiomatic C# code, to help platform developers and others work with any provider with standard implementations for caching, telemetry, tool calling and other common tasks.

  • Final .NET 9 Preview Ships with Go-Live License

    Visual Studio developers can now download the SDK for .NET 9 Release Candidate 2 with a go-live license, meaning devs get Microsoft support for production applications even before the framework reaches general availability next month.

  • Upcycle Your Old Laptops into a Kubernetes Cluster

    Learn about Windows-to-Linux conversions and how to break and fix cloud containers -- all while helping to save the world from e-waste with some "sheer geeky fun."

  • Visual Studio's Future: Live Help to 'AI-ify Your App'

    Visual Studio guru Mads Kristensen provided a peek into the IDE's AI future, explaining how while in live-coding it will identify opportunities for your own app to use AI to your advantage.

Subscribe on YouTube