Monday 27 June 2011

Object and Collection Initialization

C# 3.0 Introduced a short hand you can use while instantiating new instances of objects.

You can change the following code:

Car myMustang = new Car();
myMustang.Manufacturer = "Ford";
myMustang.YearOfMake = "1969";

To something much neater like:

Car myMustang = new Car()
{
     Manufacturer = "Ford",
     YearOfMake = "1969"
};

You can also nest the object initialization:


Car myMustang = new Car()
{
     Manufacturer = "Ford",
     YearOfMake = "1969",
     Seat = new Seat 
     {
            Material = "Leather";
            Color = "White";
     }
};

And it also works for Collections:


List<Car> myGarage = new List<Car> 
{
     new Car()
     {
          Manufacturer = "Ford",
          YearOfMake = "1969"
     },
     new Car()
     {
          Manufacturer = "Lamborghini",
          YearOfMake = "1983"
     }
 };

Click here to check out MSDN or more information on Object and Collection Initializers.

Click here to see how to initialize a Dictionary using Object Initializers.

No comments:

Post a Comment