Thursday, February 28, 2008

C#.NET 3.5 - Automatic Properties

Automatic Properties
There is no. of new features introduced in C# to enable developers to write simple and short code. Properties
is best when we want to control or validate values to be stored in fields/members, Many a times in order to grant access to private fields of class we declare appropriate public properties. So we declare it as

public class Employee {

private string _EmpName;
private int _Salary;

public string EmpName {

get {
return _EmpName;
}
set {
_EmpName = value;
}
}

public int Salary{

get {
return _Salary;
}
set {
_Salary = value;
}
}
}

With automatic properties we need not provide full definition of property, In fact compiler generates default definition which is simple assignment and retrieval of values. if you wish to add you own logic then automatic properties is not for you.

public class Employee {
public string EmpName { get; set; }
public int Salary{ get; set; }
}

Above code in C#.net 3.5 at compile time expands and generates code (in target output file) as seen in first (more verbose) implementation above.

So obviously when you have need of simple assignment and retrieval of values this feature is quite useful as it makes code short and more clean for readibility. you may also apply attributes to Auto Properties eg.

public class Employee
{
[Obsolete("Changed to ...",true)]
public string EmpName { get; set; }
public int Salary { get; set; }
}

Also to make property as Readonly or WriteOnly you can add access modifier (private) next to the set or get. This allow you to internally modify the member, while publicly providing "read only" or "write only" access.

public class Employee
{
public string EmpName { get; private set; }
public int Salary { get; private set; }

public void method1()
{
EmpName = "Jignesh"; //allowed
Salary = 100000; //allowed
}
}

private void Form1_Load(object sender, EventArgs e)
{
Employee x = new Employee();
x.Salary = 2000; // Not allowed.
}

No comments: