Collection initializer for List<myCustomClass> not working giving "; expected" compile error. Why?

534 Views Asked by At

I am trying to initialize a generic collection List something like this:

List<MyCustomClass> myCustomClassList = new List<MyCustomClass>() {myCustomClassInstance1, myCustomClassInstance2};

I am getting the compile error "; expected". I don't understand this. Shouldn't I just be able to initialize this collection like this?

2

There are 2 best solutions below

3
On BEST ANSWER

What version of .NET are you using? Collection initializers only work in .NET 3.5 and higher

0
On

Collection Initializers are part of the C# 3.0 specification and not the .Net Framework/Libraries. The earliest implementation that uses C# 3.0 is VS2008, and the .Net 3.5 framework. You can build against earlier versions of the framework. If you are compiling via script from the command-line, or other IDE, make sure you are referencing the appropriate toolchain: C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe