In the past I've initialized arrays using the full initialization syntax:
int[] arr = new int[1] { 1 };
but once I found out I didn't need to specify the type during initialization I stopped doing that:
int[] arr = { 1 };
I looked into jagged arrays again recently and found a very peculiar issue with this syntax:
int[][] jag = { { 1, 2 }, { 3 } };
The above code is NOT valid, which puzzles me. Furthermore, this syntax IS fine:
int[][] jag = { new []{ 1, 2 }, new []{ 3 } };
Clearly the only difference here is the "new" keyword. Normally, in other languages, the "new" keyword signifies that the variable is going to be a reference type, but in C# arrays are always reference types, so there really is no need to specify "new" for arrays. Does anyone know why I need to specify it here in this jagged array initialization? Is this a bug, or maybe just an unimplemented compiler feature?
Is this a bug?
Nope.
Does anyone know why I need to specify it here in this jagged array initialization?
There is no fundamental theoretical reason why the C# language must allow the array initializer syntax only for rectangular multidimensional arrays and not for jagged multidimensional arrays.
The feature you want does not exist because no one ever designed, specified, implemented, tested, documented and shipped that feature. That's because the feature could reasonably be characterized as very, very unimportant compared to pretty much any other possible feature you could spend time on. Features are expensive; the design team tries to spend time on features that solve real user problems.
Little "sugar" features like the one you propose do get implemented; expression-bodied methods, for example. But almost every program contains small methods. The vast majority of programs do not contain even one jagged, initialized-once array, so this feature would be work that saves almost no one half a dozen keystrokes. Not worth it.
maybe just an unimplemented compiler feature that will be fixed in a future version of C#?
If this feature is important to you, well, the design and implementation process is open. Feel free to propose, design, specify, implement, test and document the feature, and see if they accept your pull request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With