h1

Object Initialization in C# 3.0

February 19, 2008

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.

3 comments

  1. Can you do this?

    List customer = new List
    {
    new Customer{ FirstName=”", Address=”"}
    };


  2. Yes, you can. Assuming that WordPress removed the generic parameter - Customer, that you are passing to List in your comment.


  3. [...] Object Initialization [...]


Leave a Comment