Auto-Implemented Properties in C# 3.0

Posted by Techie Cocktail | 2:02 PM | | 0 comments »

Auto-Implemented Properties is one of the new features in C# 3.0. Let’s see what are they, how to implement them and how it makes our lives easy.

To create simple read-write, read-only properties in a class, you write many lines of code. The properties are public in nature and their underlying data are stored in private variables.

For example, check the below sample class having a few properties.


public class employee
{
private string _name;
private string _designation;
private double _salary;

public string name
{
get
{
return _name;
}
set
{
value = _name;
}
}

public string designation
{
get
{
return _designation;
}
set
{
value = _designation;
}
}

public double salary
{
get
{
return _salary;
}
}

public void GetSalary()
{
switch (designation)
{
case "Junior":
{
_salary = 2000;
}
break;
case "Senior":
{
_salary = 4000;
}
break;
case "Manager":
{
_salary = 10000;
}
break;
}
}
}


As you see in order to create a simple property we had to write extra lines of code. And if the class has 6-10 properties you would spend time writing those extra lines of code for each property.

This issue has been simplified by VS Team in C# 3.0 by introducing 'prop' (for 'read-write' property) and 'propg' (for 'read-only' property). In your code view, in your class, simply type 'prop' and hit tab twice to get your property created. Your property looks like this.


public string Name { get; set; } //read-write property
public double Salary { get; private set; } //read-only property


Just this one line of code. You do not have to create any private variable to store its underlying data. .Net takes care of it.


public class employee
{
public string Name { get; set; }
public string Designation { get; set; }
public double Salary { get; private set; }

public void GetSalary()
{
switch (Designation)
{
case "Junior":
{
Salary = 2000;
}
break;
case "Senior":
{
Salary = 4000;
}
break;
case "Manager":
{
Salary = 10000;
}
break;
}
}
}


The code size has reduced with the use of Auto-Implemented Properties. This has nothing to do with performance as the compiler would generate the same code as the previous traditional implementation. The benefits of using them are the approach towards encapsulation, save time to write the extra lines of code.

But,
if you wanted to implement some event notification or any code inside the property than just declaring a simple property, you would have to go back to the old implementation approach.

References:
a. Inside Microsoft
b. MSDN

0 comments