TOC
C# 3.0:

Collection Initializers

Just like C# 3.0 offers a new way of initializing objects, a new syntax for initializing a list with a specific set of items added to it, has been included. We can use the Car class from the last chapter:

class Car
{
    public string Name { get; set; }
    public Color Color { get; set; }
}

If we wanted to create a list to contain a range of cars, we would have to do something like this with C# 2.0:

Car car;
List<Car> cars = new List<Car>();

car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
cars.Add(car);

car = new Car();
car.Name = "Golf";
car.Color = Color.Blue;
cars.Add(car);

Using object initializers, we could do it a bit shorter:

List<Car> cars = new List<Car>();
cars.Add(new Car { Name = "Corvette", Color = Color.Yellow });
cars.Add(new Car { Name = "Golf", Color = Color.Blue});

However, it can be even simpler, when combined with collection initializers:

List<Car> cars = new List<Car> 
{ 
    new Car { Name = "Corvette", Color = Color.Yellow },
    new Car { Name = "Golf", Color = Color.Blue}
};

Or in the one-line version, which does exactly the same:

List<Car> cars = new List<Car> { new Car { Name = "Corvette", Color = Color.Yellow }, new Car { Name = "Golf", Color = Color.Blue} };

10 lines of code has been reduced to a single, albeit a bit long, line, thanks to object and collection initializers.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!