How to use Auto Implemented Properties in C# ?

Want to know what is Auto Implemented properties in C# and how to use it in your .NET application?. This blog post explains more about it.

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
                  return id;


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; }

What is the use of auto implemented properties in C# ?

We do not require private field to be defined explicitly. This is all done implicitly through this syntax. 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.