Object initializers not working on the <T> list

List<Car> oUpdateCar = new List<Car>(); oUpdateCar.Add(new Car()); oUpdateCar[0].name = "Color"; oUpdateCar[0].value = "red"; oUpdateCar.Add(new Car()); oUpdateCar[1].name = "Speed"; oUpdateCar[1].value = "200"; 

The above code works, but I want to initialize it when I create a list as shown below,

 List<Car> oUpdateCar = new List<Car> { new Car{ name = "Color"; value = "red";} new Car{ name = "Speed"; value = "200";} } 

The code above does not work. What am I missing. I am using C # .NET 2.0. Please, help.

+3
source share
2 answers

Initializers for collections and objects are new to C # 3.0; they cannot be used in Visual Studio 2005.

Also, this invalid syntax is even in C # 3; you need to replace the commas ( , ) with commas ( , ) inside the object initializers and add a comma between each object in the collection initializer.

+6
source

Collection initializers are part of C # 3.0, and the syntax is as follows:

 List<Car> oUpdateCar = new List<Car> { new Car { name = "Color", value = "red" }, new Car { name = "Speed", value = "200" } }; 
+6
source

Source: https://habr.com/ru/post/1386520/


All Articles