Search

Mar 13, 2009

Automatic Properties in C# 3.0

Automatic properties are introduced in 3.0 of C#. Using automatic properties you can save your lots of time and typing.

Up to now we were writing following code to create single property.

public class PropertyTest
{
private string _strTest;

public string strTest
{
get { return _strTest; }
set { _strTest = value; }
}
}

Now look at the automatic properties bellow.

public class PropertyTest
{
public string strTest { get; set; }
}

Only single line of code!!!
We can even restrict the get and set property, like we need set property to be private and get property to be public; yes we can do that too.

public class PropertyTest
{
public string strTest { get; private set; }
}


Although its time saver there is few limitation for this, lets list out those limitations.
  1. Automatically implemented properties must define both get and set accessors, if not have to make them abstract.

    //Gives you error
    public class PropertyTest
    {
    public string strTest { get; }
    }

    //Works fine
    abstract public class PropertyTest
    {
    abstract public string strTest { get; }
    }

  2. You can't initialize them in declaration, although you can do it into Constructor

    public class PropertyTest
    {
    public string strTest { get; set; }

    public PropertyTest()
    {
    strTest = "Test String";
    }
    }


No comments: