Wednesday, December 05, 2007

C# 3.0 : Object Initialization

Usually object can be initialized by passing value to contructor. if we want to initialize the differnt property value in different situation, we need to create a more constructor for all the situation.

Conventional Method:

class Customer
{
#region Constructors

public Customer() {}

public Customer(long customerID)
{
CustomerID = customerID;
}

public Customer(long customerID, string name)
{
CustomerID = customerID;
Name = name;
}

#endregion


#region Automatic Properties

public long CustomerID
{
get;
set;
}

public string Name
{
get;
set;
}

#endregion
}

Initialization:

Customer custObj = new Customer(1);
Customer custObj1 = new Customer(1, "Pankaj");
Customer custObj2 = new Customer();
custObj2.CustomerID = 1;
custObj2.Name = "Pankaj";

C# 3.0:

But in C# 3.0, no need to create too much contructor for initializatoin. you can initialize the property without creating the constructor.

class Customer
{

#region Automatic Properties

public long CustomerID
{
get;
set;
}

public string Name
{
get;
set;
}

#endregion
}

Initialization:

Customer custSingle = new Customer { CustomerID = 1 };
Customer cust = new Customer { CustomerID = 1, Name = "Pankaj" };


Constructor and Initialization:

you can also call the constructor and initialize the property at the same time.

Customer custConst = new Customer(1) { CustomerID = 2, Name = "Pankaj" };


First call the constructor and then initialize the property.

So finally CustomerID value will be 2 instead of 1.

No comments: