The community is working on translating this tutorial into Slovak, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
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.