These are the correct declaration and initialization ways for a simple array of string in C#.
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 you can obtain arrays from Linq ToArray() extensions on IEnumerable<T>.
Also note that in the declarations above, you can replace the first two string[] on the left with var (C# 3.0+). But for third one as the information on the right is enough to infer the proper type, must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. So 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
Posted On:
27-Apr-2017 02:58