The Edge

Web application development insights written for our team, but open to the development community.

Automatic Properties in

Published on September 7, 2010

With VB10 in Visual Studio 2010 came a swag of improvements that make code both easier to write and easier to read.

One of those improvements has been with c# for a while; automatic properties.  In c# you can declare a property like so;

     public string Name { get; set; }

This will create the property called “Name”, and when compiled will create the private, member variable _Name.

In most cases where a property is declared, we never need to access the member variable associated with the property.  This is particularly true of our domain entities where properties are often used to simply store data.

Now to  Up until Visual Studio 2010, a property needed to be declared and used in a way similar to this (being overridable due to our use of nHibernate);

    Public Overridable Property FirstName() As String
            Return m_FirstName
        End Get
        Set(ByVal value As String)
            m_FirstName = value
        End Set
    End Property
    Private m_FirstName As String

This whole chunk of code can now be narrowed down to;

    Public Overridable Property FirstName() As String

That makes a big difference when putting together a large domain model or reading through a domain entity code – to see all the properties in a short, concise list.

To initialise the property with a default value (you would have typically assigned this to the member variable), you can just assign it to the property;

    Public Overridable Property Lines() As IList(Of Line) = New List(Of Line)

Or, you can use the DefaultValue attribute;

    <defaultvalue ("New Customer")> 
    Property Name() As String Implements ICustomer.Name



MSDN: Auto-Implemented Properties (Visual Basic)

Filed under:
Tags: ,

Leave a Reply