Collection Initializers
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.
Having problems with this chapter? Ask in our forums!
© net-tutorials.com 2006 - 2010