Object Initialization in C# 3.0

In older versions of C# when you create a new object and had to initialize some of its members, you had to write code similar to this –

Name name = new Name();
name.FirstName = “Fred”;
name.LastName = “Nurk”;

To make this sort of initialization easier, C# 3.0 introduces new syntax as shown below –

//Initialization with empty constructor
Name name = new Name
             { FirstName = “Fred”,
               LastName = “Nurk” 
             };

The syntax also allows constructors with parameters –

//Intialization with constructor parameter
Name name = new Name(someParameter)
            {
                FirstName = “Fred”,
                LastName = “Nurk” 
            };

You can also do nested initialization as shown below –

//Nested initialization
Customer customer = new Customer
{
    CustomerName = new Name 
       { FirstName = “Fred” },
       Address = “400, Somwhere”
};

The syntax is pretty straight forward. You can initialize any public Property or member variable, by specifying the name of the Property/variable and initializing it with a = operator. More than one member can be initialized by using the comma operator. The only thing you cannot do is call a method or initialize a private member inside the initializer.

Advertisements

5 responses

  1. Pingback: Implicitly typed arrays in C# 3.0 « Mahesh’s brain droppings

  2. Pingback: How to make Anonymous Types in ASP.NET | ArticlesRain

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