Auto Implemented Properties in .NET

If we want to create a class with a bunch of public properties , we generally do it by storing the value of the properties in private field.

Eg :

Class Student

{

           private int id;
           public int ID
           {
               get
               {
                  return id;
                }
               set
               {
                  id=value;
               }
           }

}

If this is all we need it , then in C# 3.0 and above , we can do the same more compactly and simpler .This feature is also introduced recently in VB 10.0 .

Eg :

 public int ID {get;set; }

We do not require private field to be defined explicitly , as this is all done implicitly through this syntax.i.e when we declare a Auto Implemented property, the compiler automatically creates a private field that is available only to the get and set accessors of the property.

There is another shortcut to achieve the same using code snippets.

type prop and hit tab twice

The above uses the auto implemented properties syntax , so that we can go through and create / customize the property .

If we dont want public set and public get and if we want to make this a readonly property, we can type in

propg and hit tab twice.

The result of the above would be something similar , here i have changed the datatype and Name of the property

 public int ID {	get; private set;}

We can see that a private setter is created .

Auto Implemented properties are a nice little feature in c# 3.0 and above versions that allows us to easily create accessors ( getters and setters ) for your private fields .

We can use the auto-implemented properties whenever we define a properties that does not have special logic inside the getter or setter.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

5 Responses

  1. Pingback: Auto Implemented Properties in .NET | ProgramInDotnet

Leave a Reply