| More
All posts tagged 'vb'
 


One more VB 2010 Language Feature....

Happy to see the interest in last weeks post!  I'd like to let all the VB-ers know of another very nice addition to Microsoft's BASIC language, the use of automatic properties. As you are aware, under .NET, the perferred way to encapsulate simple state data is via type properties. Much like a normal get/set method pair, .NET properties will allow the object user to safely interact with private data.  However, when doing so, it appears they are working on a public field (from a syntatic point of view). 

Before the release of .NET 4.0, VB programmers would build properties using code such as the following:

Public Class Animal

    Private animalName As String
    Public Property Name() As String
        Get
            Return animalName
        End Get
        Set(ByVal value As String)
            animalName = value
        End Set
    End Property

End Class

While the previous property definition is fine, it is a tad bit verbose, especially when all you want to do is have basic encapsulation (in other words, no checking against business rules, no error logging, etc). To simplify the amount of typing time, VB 2010 now allows you to define a property as so:

Public Class Animal
      Public Property Name() As String = ""
End Class

When processed by the compiler, it will automatically create a private backing field, and implement the get/set logic. Understand of course if you *do* require properties which do more than simply get/set a value, you will want to fall back on traditional syntax.


Posted by: Andrew Troelsen
Posted on: 4/15/2010 at 1:02 PM
Tags:
Categories: .NET
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed