Since I tend to forget in-line array expression: [Archive.is] c# – All possible array initialization syntaxes – Stack Overflow:
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 string[] array = new[] { "A", "B" }; // created populated array of length 2
…Also note that in the declarations above, the first two could replace thestring[]
on the left withvar
(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. The fourth could also use inference. So if you’re into the whole brevity thing, the above could be written asvar 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 var array = new[] { "A", "B" }; // created populated array of length 2
–jeroen