Monday, 5 September 2011

Object Initializers in C# 3.0


With C# 3.0, initializing both objects and collections have become much easier. Consider this simple Car class:
class Car
{
public string Name { get; set; }
      public Color Color { get; set; }
}
Now, in C# 2.0, we would have to write a piece of code like this to create a Car instance and set its properties:
Car car = new Car();
car.Name = "Chevrolet Corvette";
car.Color = Color.Yellow;

It's just fine really, but with C# 3.0, it can be done a bit more cleanly, thanks to the new object initializer syntax:
Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };
As you can see, we use a set of curly brackets after instantiating a new Car object, and within them, we have access to all the public properties of the Car class. This saves a bit of typing and a bit of space as well. The cool part is that it can be nested too. Consider the following example, where we add a new complex property to the Car class, like this:
class Car
{
public string Name { get; set; }
      public Color Color { get; set; }
      public CarManufacturer Manufacturer { get; set; }
}

class CarManufacturer
{
      public string Name { get; set; }
      public string Country { get; set; }
}

To initialize a new car with C# 2.0, we would have to do something like this:
Car car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
car.Manufacturer = new CarManufacturer();
car.Manufacturer.Name = "Chevrolet";
car.Manufacturer.Country = "USA";

With C# 3.0, we can do it like this instead:

Car car = new Car {
                Name = "Chevrolet Corvette",
                Color = Color.Yellow,
                Manufacturer = new CarManufacturer {
                    Name = "Chevrolet",
                    Country = "USA"
                }
            };
Or in case you're not too worried about readability, like this:

Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow, Manufacturer = new CarManufacturer { Name = "Chevrolet", Country = "USA" } };

No comments:

Post a Comment