views:

85

answers:

3
        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 is working but i want to initialize it when i create the list as below,

List<Car> oUpdateCar = new List<Car>
    {

        new Car{
        name = "Color";
        value = "red";}

    new Car{
        name = "Speed";
        value = "200";}
    }

The above code is not working. What am i missing. I am using c# .NET 2.0. Please help.

+6  A: 

Collection and object initializers are new to C# 3.0; they cannot be used in Visual Studio 2005.

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

SLaks
is there any alternative in c# 2.0 ?
Jebli
No, there isn't.
SLaks
+5  A: 

Collection initializers are part of C# 3.0 and the syntax is like this:

List<Car> oUpdateCar = new List<Car>
{
    new Car
    {
        name = "Color",
        value = "red"
    },

    new Car
    {
        name = "Speed",
        value = "200"
    }
};
Darin Dimitrov
is there any way to do this in using c# 2.0 or is it possible to use c# 3.0 in vs 2005 ?
Jebli
@Jebli, no there isn't. The C# 2.0 compiler doesn't understand collection initializers.
Darin Dimitrov
@Nick, modified my post according to your suggestion.
Darin Dimitrov
A: 

Collection and object initializers are new to C# 3.0; they cannot be used in Visual Studio 2005. Thanks @sLaks and @Darin's answer.

Jebli