TOC

This article has been localized into Dutch by the community.

C# 3.0:

Collection Initialiseerders

Net zoals C# 3.0 een nieuwe manier biedt om objecten te initialiseren, zit er nu ook een nieuwe syntaxis bij om een lijst met een specifieke set toegevoegde items te initialiseren. We gebruiken de Car class uit het vorige hoofdstuk:

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

In C# 2.0 moesten we dit doen om een lijst met auto's de maken:

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);

Met object initialiseerders kan het wat korter:

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

Maar het kan nog simpeler als we het combineren met collection initialiseerders:

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

Of, in de één regel versie, die precies hetzelfde doet:

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

10 regels code zijn teruggebracht tot een enkele, alhoewel wat lange regel, dankzij object en collection initialiseerders.


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!