C# tricks: Array initialization in C# 3.0

I found pretty slick new feature in C# 3.0 that I haven’t seen anyone mentioning before.

In C# 2.0 to initialize List<T> inline you had to use arrays, like

List<string> keys = new List<string>(new string[]{"key1"});

As you probably already know, in C# 3.0 you can initialize collections in in similar way like you did with arrays in C# 2.0:

List<string> keys = new List<string>(){"key1"};

This has been said many times in many places. What I missed however, was that syntax for initializing arrays changed as well. Now you can simply write:

string[] keys = new[]{"key1"};

Did you know that?

Technorati Tags: ,

Comments

EnocNRoll says:

yeah, I missed that. Sweet!

Marek says:

You can also write:

int[] liczby = { 6, 6, 6 }; // without new[]

int[][] liczby2 = {
new int[] { 0, 1, 2, 3, 4 },
new int[] { 4, 3, 2, 1, 0 },
};

Did you know THAT? 😉

Marek,

Hmmm, this is slick. And it seems to be working with C# 2.0 as well. How come I didn’t know that?

BTW,
for MD array you can use new[] instead of new int[] to make it even smaller. (in C# 3.0)

walt says:

string[] keys = new[]{"key1"};
doesn’t that just initialize the first value of the array. Or rather, set the array length to 1 and use the only value to initialize the only element!
int [] theintarray = new []{myintvar};
Is there something clever that does this initialization:
for(int i=0;i<theintarray.Length;i++)theintarray[i] = myintvar;
I’m looking for a repitition factor in the initialization list.

@walt

yes, it does, which is precisely what you need most of the time.
If you want to initialize larger array with the same value everywhere you need a loop.