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?

2
  • Why would you expect an error in the second version? Commented May 14, 2015 at 0:20
  • Ok, thanks. I was not aware its possible to do both ways. I may delete this posting if its asked. Commented May 14, 2015 at 0:22

2 Answers 2

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.

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

Comments

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.

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.