I see from this question that there are four permissible ways to initialise an array in C#. Taken from the accepted answer:
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
The linked answer clarifies that you can also make the above expressions terser, with the exception of the third, using the var
keyword:
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
My question is: why would you ever wish to use the new
syntax for an array? Is there any performance benefit to using either var array = new string[] { "A", "B" }
instead of string[] array = { "A" , "B" }
?