Automatic Properties in .Net

 

As we know we have properties in .Net. By using properties we can set the value and we can set the value. In .Net 4.0 we have automatic properties, where only syntax is differs as compared to previous syntax.

 

First we check what is the syntax of property before .Net 4.0. The old syntax of property contains get and set methods, by using one private variable we have to set the value for property as shown below.

 

        private string sName = string.Empty;

        public string Name

        {

            get { return sName; }

            set { sName = value; }

        }

 

As we know properties are used to set the value or we can get the value from property. But to define one property we are using one private variable just to set or get the value. In .Net 4.0 we have Automatic properties where we can easily avoid this private variable as shown below.

 

        public string Name       

        {

            get;

            set;

        }

 

We can easily create automatic property by typing prop and hitting the Tab key twice.

 

But by using Automatic properties we cannot add any logic for set and get method. And another disadvantage is we cannot have only get method or only set method as shown below.

        

        public string Name       

        {

            get;    //we will get compile time error

        }

 

        public string Name

        {

            set;    //we will get compile time error

        }

 

If we have only get or set method compiler produces errors as shown above.