Alex Rivera | Logout

Create List<int> with values at compile time

Asked 2009-04-27T10:33:05.193
36

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)?

Edit
Report

1 Answer

6

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.

answered 2009-04-27T10:38:15.213

Your Answer