Thursday, January 3, 2008

C# : Object Initializers

In C#, when declaring an object or collection, you may include an initializer that specifies the initial values of the members of the newly created object or collection.

In C# 3.0, the new syntax for object creation and initialization in a single step. An object initializer consists of a sequence of member initializers, contained in '{ } 'braces and separated by commas. Each member initializer assigns a value to a field or property of the object.

For example,

using System.Collections.Generic;

namespace VS2008New
{
public class Employee
{
public int ID { get; private set; }
public string Name { get; set; }
public string Destination { get; set; }
public int Experiance { get; set; }

public Employee(int id)
{
ID = id;
}
public override string ToString()
{
return Name + "\t" + Destination + "\t" + Experiance + "\t" + ID;
}
}

class Program
{
static void Main(string[] args)
{
// In C# 2.0
Employee emp = new Employee(1000)
emp.Name = "Tony";
emp.Destination = "Salesman";
emp.Experiance = 5;
Console.WriteLine(c);

// In C# 3.0
Employee emp1 = new Employee(1001)
{ Name = "Rangoli Kannan", Destination = "Developer", Experiance = 4 };
Console.WriteLine(emp1);
}
}
}
Now build and run this application, we get the result like this,


Share your thoughts with me !!!
- Rangoli