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.

4 Comments

  1. Mark Spizer May 2, 2010 Reply
  2. Павел May 22, 2010 Reply
  3. Rockon May 26, 2010 Reply
  4. Chester Beard May 30, 2010 Reply
  5. Auto Implemented Properties in .NET | ProgramInDotnet August 7, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

JavaScript Tutorial #2 - Syntax of JavaScript
The JavaScript elements and statements are placed within the script tag within the HTML page.You...
How to Get the List of User Tables in SQL Server?
If you need to retrieve the list of the tables created by the users in SQL Server, you can do that e...
Different Ways to get the computer name in c#
There are different ways in which the developers can get the computer name in their .NET application...