-1

What will be the difference between using keyword new in declaring a new array or not using it? I saw something like that on the internet but didn't fully understand the difference: new keyword on the right side of the assignment using this syntax. This is only possible during the array’s declaration.

for example:

string[] names = {"Joe", "Sally", "Thomas"};

string[] names = new string[] {"Joe", "Sally", "Thomas"};
  • 1
    Does this answer your question? [All possible array initialization syntaxes](https://stackoverflow.com/questions/5678216/all-possible-array-initialization-syntaxes) – Drag and Drop Apr 10 '21 at 07:21
  • There’s no difference; the C# language syntax - increasingly so with later versions - just allows you to use the more compact/terse version when the extra bits in the more verbose version add little value. – sellotape Apr 10 '21 at 07:25

2 Answers2

3

The difference is "new string[]".

I mean, these do exactly the same thing:

string[] names = new string[3] {"Joe", "Sally", "Thomas"};
string[] names = new string[] {"Joe", "Sally", "Thomas"};
string[] names = new [] {"Joe", "Sally", "Thomas"};
string[] names = {"Joe", "Sally", "Thomas"};

Now, consider using var. This works:

var names = new string[3] {"Joe", "Sally", "Thomas"};
var names = new string[] {"Joe", "Sally", "Thomas"};
var names = new [] {"Joe", "Sally", "Thomas"};

But this does not:

var names = {"Joe", "Sally", "Thomas"};

See Why can't I use the array initializer with an implicitly typed variable?.

Theraot
  • 31,890
  • 5
  • 57
  • 86
0

There's effectively no difference after the code is compiled. Which one you should use is based on preference.

I often use https://sharplab.io for comparing the original and compiled versions of code as seen below.

In this case, the compiler is able to tell what type the new array should be based on the variable declaration string[] names1.

Your original code:

string[] names1 = {"Joe", "Sally", "Thomas"};

string[] names2 = new string[] {"Joe", "Sally", "Thomas"};

After compiling:

string[] array = new string[3];
array[0] = "Joe";
array[1] = "Sally";
array[2] = "Thomas";
string[] array2 = new string[3];
array2[0] = "Joe";
array2[1] = "Sally";
array2[2] = "Thomas";
Exanite
  • 66
  • 2
  • 5