Joshua Girard Joshua Girard - 3 months ago 18
C# Question

All possible C# array initialization syntaxes

What are all the possible array init syntaxes that are possible with C#?

It gets really confusing to know if it is an array initializer or a separate declaration.

Note: I've searched MSDN, googled it, but there isn't an all-in-one guide.

I'm using .NET 3.5 and C#.

Answer

These are the current declaration and initialization methods for a simple array.

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2

Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.

Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. So if you're into the whole brevity thing, the above could be written as

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2