Object and Collection Initializers (C#)

C# 3.0 was released as a part of the Microsoft .NET 3.5 Framework. In this blog post, I’ll cover the object and collection intitializers feature of C# 3.0. Initializers introduce a concise syntax that combines object creation and initialization in a single step. It even allows for parentheses to be optional for paramaterless constructors as shown below:

 
Point p = new Point {
   X=3,
   Y=99 };
 
Employee myEmployee = new Employee() {
   Name       = "John Doe",
   Position   = "Marketing Manager",
   Department = "Marketing" };
Initializers work very well with constructors as shown below:. The following code snippet shows an instance where a parameterized constructor is called along with remaining properties initialized.
 
class Customer
{
   public Customer(string customerKey) { … }
   public string CustomerKey { get { … } }
   public string ContactName { get; set; }
   public string City { get; set; }
}
 
var c = new Customer("MARKS") {
   ContactName = "Mark Strawmyer",
   City = "Indianapolis"
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: