tags:

views:

48

answers:

3

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);
+10  A: 

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.

JaredPar
+1  A: 

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.
Jay
List is a lot of pretty useless code considering you can declare a new array inline in the call to the List<T> constructor to get he same effect.
Justin Niessner
Does C# 2.0’s `List<T>` not have `AddRange` yet?
Timwi
+2  A: 
int[] values = { 1, 2, 3, 4 };
List<int> ints = new List<int>(values);
leppie