Why can not I use the table initialization syntax separate from the array declaration?

advertisements

I can do this with an integer:

int a;
a = 5;

But I can't do this with an integer array:

int[] a;
a = { 1, 2, 3, 4, 5 };

Why not?

To clarify, I am not looking for the correct syntax. That I can look up. I know that this works:

int[] a = { 1, 2, 3, 4, 5 };

Which would be the equivalent of:

int a = 5;

What I am trying to understand is, why does the code fail for arrays? What is the reason behind the code failing to be recognised as valid.


The reason there is a difference is that the folks at Microsoft decided to lighten the syntax when declaring and initializing the array in the same statement, but did not add the required syntax to allow you to assign a new array to it later.

This is why this works:

int[] a = { 1, 2, 3, 4, 5 };

but this does not:

int[] a;
a = { 1, 2, 3, 4, 5 };

Could they have added the syntax to allow this? Sure, but they didn't. Most likely they felt that this usecase is so seldom used that it doesn't warrant prioritizing over other features. All new features start with minus 100 points and this probably just didn't rank high enough on the priority list.

Note that { 1, 2, 3, 4, 5 } by itself has no meaning, it can only appear in two places:

  • As part of an array variable declaration:

    int[] a = { 1, 2, 3, 4, 5 };
    
    
  • As part of an array creation expression:

    new int[] { 1, 2, 3, 4, 5 }
    
    

The number 5, on the other hand, has a meaning everywhere it appears in C#, which is why this works:

int a;
a = 5;

So this is just special syntax the designers of C# decided to support, nothing more.

This syntax is documented in the C# specification, section 12.6 Array Initializers.