1

I had just started learning C# and using Tutorials Point to do this. In the section on arrays, I keep seeing arrays declared as

string[] sarray = { "Hello", "From", "Tutorials", "Point" };

Or other times like this:

int [] marks = new int[5]  { 99,  98, 92, 97, 95 };

Coming from c++, the first method of declaration wasn't all that new to me, but the second one is the one I don't understand. The question is if the array is going to dynamically initialised, then why use the brace enclosed initializer list to specify the contents of the array?

Is there an advantage to initialising that second one the way it has been done?

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 1
    possible duplicate of [All possible C# array initialization syntaxes](http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes) – Dustin Kingen Sep 23 '13 at 16:09
  • The difference between the first and second example is syntax. There are several styles to initialize arrays. I would recommend using a [`List(T)`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) since it behaves more like the C++ `vector` type. – Dustin Kingen Sep 23 '13 at 16:12

2 Answers2

6

No advantage at all. It's a coding-preference thing.

You can even leave out just the size portion such as:

int[] marks = new int[] {99, 98, 92, 97, 95};

Check out the MSDN for more info: http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

awudoin
  • 541
  • 2
  • 8
  • 1
    you don't even need the int[] part on the right, `int[] abc = new[] { 99, 98, 92, 97, 95 };` works just fine – Save Sep 23 '13 at 16:13
  • Ok thanks for this, I was just thinking it had something to do with being able to pass one to a function not being able to do that with the other due to the way they have both been initialised – smac89 Sep 23 '13 at 16:18
3

The first statement is implicitly the same as

string[] sarray = new string[5] { "Hello", ... };

There is no advantage to one style over the other, save personal preference. I would tend to write the second statement as

var marks = new [] { 99, 98, ... };
Preston Guillot
  • 6,493
  • 3
  • 30
  • 40