kateroh
kateroh

Reputation: 4416

Initialization of Lists that makes csc 2.0 happy

I need to initialize a bunch of lists and populate them with lots of values during initialization, but csc 2.0 compiler that i have to use doesn't like it. For example:

List<int> ints = new List<int>() { 1, 2, 3 };

will produce the following compiler error:

error CS1002: ; expected

Is there a way to initialize a list that will make csc 2.0 compiler happy without doing something ugly like this:

List<int> ints = new List<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);

Upvotes: 1

Views: 362

Answers (3)

Jay
Jay

Reputation: 57959

Since you're initializing a bunch of lists, shorten the syntax as much as possible. Add a helper method:

 private static List<T> NewList<T>(params T[] items)
 {
     return new List<T>(items);
 }

Call it like this:

 List<int> ints = NewList(1,2,3);
 List<string> strings = NewList("one","two","three");
 // etc.

Upvotes: 1

leppie
leppie

Reputation: 117280

int[] values = { 1, 2, 3, 4 };
List<int> ints = new List<int>(values);

Upvotes: 2

JaredPar
JaredPar

Reputation: 755141

You're using a feature called collection initializers which was added in C# 3.0 and hence is not present in the C# 2.0 compiler. The closest you will get syntax wise is using an explicit array passed to the List<T> constructor.

List<int> ints = new List<int>(new int[] { 1, 2, 3 });

Note: This approach produces substantially different code than the C# collection initializer version.

Upvotes: 10

Related Questions