Wednesday, May 7, 2008

Object and Collection Initializers

This is an interesting feature that will seem more valuable once you go through the below example.

Imagine a class Employee which has the properties like Name and ID

To add two employees and to list them required the following code till c# 2.0.




using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee("Naveen",1);
Employee emp2 = new Employee("Jonny", 2);

Console.WriteLine("Employee List :");
Console.WriteLine("----------------");
Console.WriteLine("ID Name");
Console.WriteLine("----------------");
Console.WriteLine("{0} {1}", emp1.ID, emp1.Name);
Console.WriteLine("{0} {1}", emp2.ID, emp2.Name);
Console.Read();
}

public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

private int id;
public int ID
{
get { return id; }
set { id = value; }
}

public Employee(string Name, int ID)
{
this.Name = Name;
this.ID = ID;
}
}
}
}



Now watch on whats new in c# 3.0. Life is simplified with the the Object Initailizers.





using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee() { Name = "Naveen", ID = 1 };
Employee emp2 = new Employee() { Name = "Jonny" };

Console.WriteLine("Employee List :");
Console.WriteLine("----------------");
Console.WriteLine("ID Name");
Console.WriteLine("----------------");
Console.WriteLine("{0} {1}", emp1.ID, emp1.Name);
Console.WriteLine("{0} {1}", emp2.ID, emp2.Name);
Console.Read();
}

public class Employee
{
public string Name { get; set; }
public int ID{get;set;}
}
}
}


The improvements
1. if check the employee class you will find it much simpler, with no much code.
The constructor is removed, as well as the private variables are missing.
Still the code is running smoothly with data.
When the C# "Orcas" compiler encounters an empty get/set property implementation
like above, it will now automatically generate a private field for you within your
class, and implement a public getter and setter property implementation to it.

2. When creating a instance of the Employee class we can see some new things.
Here comes the concept of object Initializers. while creating the instance itself
we can specify which property is to be set with what value. This helps to avoid
creating overloads for the constructor.

Hope you have enjoyed the example. Try some more and explore the concepts.
Catch you soon with some other stuffs.
:-)

No comments: