Tips and Tricks from my Experience

C# 3.0 – What’s New : {Properties}-Part2

Posted in Uncategorized by Chakravarthy on October 12, 2007

Property of the class can be considered as the mechanism of accessing the private variables of the class. In other words, properties act as wrappers to the private variables. Though, the new feature related to this is not so great from the point of technology, but highly meaningful from the developer point of view. In a large class code, having many fields and exposed as Properties, it is really difficult to remember the private fields association with the respective definition of properties. The new feature of Properties in C# 3.0 language specification says that the developer doesn’t require to define the private variables that are associated with the respective properties. During the good olden days, we are used to the following coding mechanism to declare the property via a private variable.

        // The private Variable declaration
        string strEmpName;

        // Property Declaration
        public string EmployeeName
        {
            get {
                // Returning the value from the private variable
                return strEmpName;
                }
            set {
                // Assigning the value to private Variable
                strEmpName = value; 
                }
        }

But hence forth, by using the C# 3.0 version, we doesn’t require to define as above but just as simple as mentioned below

        public string EmployeeName { get; set; }

How simple is this, by this method we doesn’t require to remember which is property and which is a private variable. But bottom line remains the same as of the old tradition, the only thing that every one has to remember is that, there is no need to declare a private variable and association of the same with the exposed property. Beneath the code, the compiler creates a private variable for each property that you define as such. To justify, use any reflector to understand the emitted IL code and the Assembly signature. You will surprise to note that a separate private variable is associated by the compiler.

Technorati Tags: