TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

C# 3.0 Object Initializers

Object Initializers allows you to initialize the object members without an overloaded constructor or with out setting the properties after object creation.Means the initial value of the class property variables can be set directly during instantiation of the object itself, in C# 3.0 using Object initializers.

Object Initializers allows you to initialize the object members without an overloaded constructor or with out setting the properties after object creation.Means the initial value of the object property variables can be set directly during instantiation of the object itself in C# 3.0 using Object initializers.

Consider the class,

Class Employee
{
  private string empId;
  private string EmpName;
  private string Address;
  private int Salary;
 
  public string EmpId
  {
    get {return empId; }
    set {empId = value;}
  }
  public string EmpName
  {
    get {return empName;}
    set {empName = value;}
  } 
  public string Address
  {
    get {return address}
    set {address = value;}
  }
  public int Salary
  {
    get {return salary;}
    set {salary = value;}
  }
}

Till C# 2.0 for setting the initial state of an object we need to create an overloaded constructor
and set the corresponding property values as below
Employee employee = new Employee();
employee.EmpId = "EMP001";
employee.EmpName = "Rajeev";
employee.Address = "Bangalore,India";
employee.Salary = 50000;

or in another way, using constructor overloading like

public Employee(string id,string name,string address,int sal)
{
employee.EmpId = id;
employee.EmpName = name;
employee.Address = address;
employee.Salary = sal;
}

and then create instance by using the overloaded constructor

Empolyee employee = new Employee("EMP001","Rajeev","Bangalore,India",50000);

But from C# 3.0 onwards this is made easier.Without an overloaded constructor
it is possible to set the initial state of an object directly during instantiation
as below


Employee employee = new Employee {

EmpId = "EMP001, EmpName = "Rajeev", Address = "Bangalore,India", Salary = 50000 };

Collection Initializers

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading