samsalisbury.net

Archive for September, 2009

Automatic properties in VB.NET

by on Sep.01, 2009, under ASP.NET, VB.NET

The mind sometimes boggles at Microsoft’s implementation of VB.NET. One of these logic-defying mysteries is why VB.NET, in the .NET Framework 3.5, does not support automatic properties using similar syntax to C#. Automatic properties are a way to generate a private field, along with a two accessor methods (get and set) with independant levels of data hiding. They look like this in C#…

// A publically readable but only privately writeable string
public string aStringProperty { get; private set; }

The code above is expanded by the compiler to create a private string field, a private set method and a public get method, something that would look something akin to this (with the addition of having the ‘=’ operator overloaded to provide automatic calls to these accessor methods when necessary)…

// A publically readable but only privately writeable string
private string _StringProperty;
public string get_StringProperty { return _aStringProperty; }
private string set_StringProperty { _aStringProperty = value; }

However in VB.NET the situation is much worse! Look at this mess…

Private _StringProperty As String
Public Property StringProperty As String
	Get
		Return _StringProperty
	End Get
	Private Set(ByVal value As String)
		_StringProperty = value
	End Set
End Property

That’s right, 9 lines of code in VB.NET, that can be written using only 1 in C#. And VB is meant to be easier?!

What’s so great about properties anyway?

One of the main reasons I use properties as opposed to just public data members in my ASP.NET applications is that once you have defined a web user control with public properties, these properties added to the Intellisense database, helping you out when inserting the web user control into another control or page. This is mighty useful when writing a control that will be consumed by people who don’t know, or shouldn’t need to know the internal workings of the control. However, simple public fields, i.e. those declared in VB.NET thusly…

Public SomePublicField As String

…do not get this Intellisense treatment. They can be manually typed into the aspx code as attributes to the web user control, however without Intellisense to guide the way, many developers will thus assume that the attribute with this name is not available to them.

Maybe Microsoft should look into adding Intellisense support for such simple public data members? But I guess that’s something for the commenters to discuss! Even better would be proper automatic properties for VB.NET, as there seems to be something good about only exposing properly encapsulated properties to the aspx code.

3 Comments :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Archives

All entries, chronologically...