Tuesday, April 01, 2008

What's new in C# 3.0 ?? - Part 1

I'll be writing -in shaa Allah- a series of posts about the new features in C# 3.0.. I'll start this one with the improvements that were done on C# 2.0..

1) Auto-Implemented Properties:
How much time does the one spend writing private members in a class & writing their public properties.. too much ha? .. I hear someone saying "you can use snippets" .. ok, that will be fine yet this is still too much.. so here is one of the enhancements done in C# 3.0 which is the auto-implemented properties.. instead of writing sth like this..

class Employee
{
private string
empName;
public string
EmployeeName
{
get
{ empName = value; }
set
{ return this.empName; }
}
}

All you need now is to use the auto-implemented properties instead..

class Employee
{
public string
EmployeeName { get; set; }
}


The question regarding accessing private members from inside the class, well.. as there's no private members (or they are hidden), you have to use the properties to access them too..

2- Object Initializers:
Sometimes we want to set a lot of properties of an object while initializing it, but yet this isn't supported in any of the class constructors..so here comes the importance of the object initializers feature.. which will be very helpful while working with win forms & many of the .net libraries in setting properties more easily..

static void Main(string[] args)
{
Employee
e = new
Employee () { EmployeeName = "Roaa"};
}


3- Collection Initializers:
The same concept as the object initializers, but the difference is setting the values of a collection, It can be used by any collection which implements IEnumerable..

static void Main(string[] args)
{
List
<Employee>
employees = new List<
Employee>()
{

new
Employee () { EmployeeName = "Roaa" };
new
Employee () { EmployeeName = "Someone" };
new
Employee () { EmployeeName = "Roaa"};
};
}


4- var - Local Variable Type Inference
For an example as the follows, we notice the redundancy of information of the type..

Dictionary
<int,Employee>
employeesDict = new
Dictionary<int,Employee> ()

As the matter in fact, the compiler can be intelligent enough to find out about the type of the variable when a value is specified in the assignment statement.. so here comes the use of the 'var' which makes writing the code more smoother & easier..

var employeesDict = new
Dictionary<int,Employee>

but there are some restrictions on using 'var'.. as it is clear, it is for Local use only.. can't be used in return values, arguments.. etc..
Another thing, the use of 'var' doesn't affect the performance by any mean..

To be continued...