-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"};
2
  • 1
    Does this answer your question? All possible array initialization syntaxes Commented Apr 10, 2021 at 7: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. Commented Apr 10, 2021 at 7:25

2 Answers 2

5

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?.

Sign up to request clarification or add additional context in comments.

Comments

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";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.