Monday, May 24, 2010

Auto Implemented Properties – C# 3.0+

Technorati Tags: ,

Auto Implemented feature allows you to define the properties in more concise way. You need not to explicitly declare a variable & create a property for it. Complier internally declares a variable & generates code to access that variable though the property.

 Old Style of defining the properties

class Emp

    {

        // Variable/fields

        int salary;

        string name;

 

        /// <summary>

        /// Property to access salary field

        /// </summary>

        public int Salary

        {

            get { return salary; }

            set { salary = value; }

        }

 

        /// <summary>

        /// Property to access name field

        /// </summary>

        public string Name

        {

            get { return name; }

            set { name = value; }

        }

    }

New way of defining properties

Following is new way to use properties. From functionality point of view both are same. We need not to declare a variable, complier would do it internally.

    class Emp

    {

        /// <summary>

        /// Property

        /// </summary>

        public int Salary { get; set; }

 

        /// <summary>

        /// Property

        /// </summary>

        public string Name { get; set; }

    }

 

Notes

1. There is no different in term of performance in both the approaches.

2. Second approach is a concise way, code is more readable/maintainable.

3. We can use different accessor level in getter & setter, for e.g.

   

       public string Name { get; private set; }

 

4. Auto implemented must have both getter & setter field. For e.g. following code would not work

 

        // This would not compile

        public int Salary { set; }

 

5. To make read only property, setter can be declared as private. However both getter & setter can not be read only.

 

        // Read only property

        public string Name { get;  private set; }

 

        // Write only property

        public string Name { private get;  set; }

 

        // This would not compile

        public string Name { private get;  private set; }

No comments: