Object Initialization in C# 3.0

No.of Views985
Bookmarked0 times
Downloads 
Votes0
By  ayyanarj   On  16 Feb 2010 03:02:22
Tag : CSharp , How to
Object Initialization in C# 3.0
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

 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.

 

 
Sign Up to vote for this article
 
About Author
 
ayyanarj
Occupation-Software Engineer
Company-Effindi Technologies Private Limited
Member Type-Junior
Location-India
Joined date-04 Aug 2009
Home Page-http://ayyanar.blogspot.com
Blog Page-http://ayyanar.blogspot.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top