HomeVisual StudioHow to use Auto Implemented Properties in C# ?

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

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.

    3 Comments

  1. Mark Spizer
    May 2, 2010
    Reply

    great post as usual!

  2. Rockon
    May 26, 2010
    Reply

    graet

  3. Chester Beard
    May 30, 2010
    Reply

    You’ve done it once again! Incredible read!

Leave a Reply

You May Also Like

In this post, you’ll learn about the error code “SCC_E_BACKGROUNDGETINPROGRESS” returned by the Visual Studio when using the Source Control...
In this post, you’ll learn about the error code “SCC_E_UNKNOWNERROR” returned by the Visual Studio when using the Source Control...
In this post, you’ll learn about the error code “SCC_E_CONNECTIONFAILURE” returned by the Visual Studio when using the Source Control...