Search code examples
c#arrayssyntaxarray-initialization

All possible array initialization syntaxes


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


Solution

  • 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" }; // 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. The fourth could also use inference. The fifth line was introduced in C# 12 as collection expressions where the target type cannot be inferenced. It can also be used for spans and lists. 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
    var array = new[] { "A", "B" }; // created populated array of length 2
    string[] array = ["A", "B"]; // creates populated array of length 2