Sunday, March 11, 2012

Auto Implemented Properties

One of the best practices of object oriented development is to never declare public variables. Instead, you should declare private variables and assign the values and access the values via public properties.

Generally you declare properties this way
private string _name;
public string Name
{
    get{return _name;}
    set{_name=value;}
}

C# 3.0 introduced a short-cut to implement properties. Instead of manually declaring a private variable and public property to set/read values, you can simply declare a public property and compiler will automatically create a private anonymous field that can only be accessed by the get / set accessors of the property. This private field is called backing field. For example, the above property declaration can be accomplished by doing the following...

public string Name { get; set; }

This one line declaration is equivalent to what we declared manually above.

Let's consider an example...

A class with auto implemented properties

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoProperties
{
    class Student
    {

        //You can declare properties like this and C# will 
        //create backing variables to store and read values form
        public string Name{ get;set;}
        public string Address { get; set; }
        public int StudentID { get; set; }

        public void print()
        {
            Console.WriteLine("Name:={0},Address:={1},StudentID:={2}", 
                              Name, Address, StudentID);
            Console.Read();
        }
  }
    
}

Implementing the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            Student std1 = new Student();
            std1.Name = "First Student";
            std1.Address = "123 Roswell Road, Atlanta, GA 30101";
            std1.StudentID = 12345;
            std1.print();
        }
    }
}


Auto implementation is a quick way to implement properties, but there are a few limitations to this approach. You cannot implement different access levels for get and set. When you implement properties this way, both get and set are public and the class is mutable, i.e. outside code can modify the values. You also cannot implement just get, both get and set accessors must be implemented together. Similarly, if you need some code within get or set, you cannot use auto implemented properties.

This is a nice shortcut for simple classes with few properties, however you must use expanded properties declaration if you need something more.

Thank you.


No comments:

Post a Comment