2

I have new array initialised as below:

string[] someNames = new string[] { "John", "Bryan", "Annete", "Mathiew", "Joseph", "Donald", "Tom" };
string[] someNames = { "John", "Bryan", "Annete", "Mathiew", "Joseph", "Donald", "Tom" };

What is the difference? Both gives same result. I thought second one would throw an error. Why both works and which one is preferred or more correct?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
ExpertLoser
  • 257
  • 4
  • 14

2 Answers2

4

In the first case, you supply the type of array element explicitly. However, C# compiler can figure out the type of array element by analyzing the data that you supply. Your second example shows this feature.

There is absolutely no difference between the two initializers. Pick one style and use it throughout your code base for consistency.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

There is no real difference. Both work, and both give you the same thing. I'd use the latter as it is less to type and less to look at. Simplicity is always a plus.

As for a more in-depth reason, the latter way is just the first one hidden by "syntactic sugar". When compiled down there's no difference.

Rogue
  • 636
  • 8
  • 22