tags:

views:

387

answers:

4

It is possible to create an array at compile time like;

int[] myValues = new int[] { 1, 2, 3 } ;

But I would like to do something like this;

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

The compiler says No. Is there a way to do this (C# 2.0) without using LINQ (C# 3.0)?

+13  A: 
List<int> myValues = new List<int>(new int[] { 1, 2, 3 } );

This will create an intermediate array however so there may be a more efficient way of doing the same thing.

EDIT:

John Feminella suggested creating a factory method to accept a list of parameters and return a List which you could implement as follows:

List<T> CreateList<T>(params T[] values)
{
    return new List<T>(values);
}

which you can use as follows:

List<int> myValues = CreateList(1, 2, 3);
Patrick McDonald
+1 Quick-draw McGraw! :)
Matt Hamilton
One other solution is to make your own factory/extension method which accepts any parameters you like and constructs the appropriate List<int>.
John Feminella
+1 +A. Thanks... that'll do the trick.
Dead account
+2  A: 

The way you suggests was first introduced in C# 3.0 (has nothing to do with LINQ, it was a language feature that was introduced).

There's no "shortcut" (list initialization) in C# 2.0 to do just that, either new up the list and then add the numbers manually via myValues.Add, or you could do the following:

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

List of T can take an IEnumerable of T in it's constructor, of which it'll include all T's in that IEnumerable in the list created, seeing as int[] implements IEnumerable of T you can "mix and match" the features like so.

Besides that, there's no way in C# 2.0 to do a such thing that you describe.

kastermester
+2  A: 

The collection initializers are just syntax sugar, so you can use them in an application targeted at 2.0 if you compile with the 3.0 compiler.

Martin Harris
+7  A: 

Patrick has the answer you are looking for. But I wanted to add a little bit. If you want to do longer ranges of numbers and don't feel like typing them out by hand, you should look at the Enumerable.Range method. It can be used to generate a range of sequential numbers at runtime. For instance, your sample could have been written as follows

var list = Enumerable.Range(1,3).ToList();
JaredPar
+1 interesting. never saw that before ;)
Dead account
Thanks! Found this very useful on current project. :)
Aros