Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting c# new from jagged array initialization

From: http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:

int[][] jaggedArray3 = 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

What does it mean?

Why is it ok to omit new in:

int[]    arrSimp = { 1, 2, 3 };
int[,]   arrMult = { { 1, 1 }, { 2, 2 }, { 3, 3 } };

but not possible in:

int[][,] arrJagg = {new int[,] { { 1, 1} }, new int[,] { { 2, 2 } }, new int[,] { { 3, 3 } } };
like image 280
user206334 Avatar asked Dec 27 '22 10:12

user206334


1 Answers

First off, what a coincidence, an aspect of your question is the subject of my blog today:

http://ericlippert.com/2013/01/24/five-dollar-words-for-programmers-elision/

You've discovered a small "wart" in the way C# classifies expressions. As it turns out, the array initializer syntax {1, 2, 3} is not an expression. Rather, it is a syntactic unit that can only be used as part of another expression:

new[] { 1, 2, 3 }
new int[] { 1, 2, 3 }
new int[3] { 1, 2, 3 }
new int[,] { { 1, 2, 3 } }
... and so on

or as part of a collection initializer:

new List<int> { 1, 2, 3 }

or in a variable declaration:

int[] x = { 1, 2, 3 };

It is not legal to use the array initializer syntax in any other context in which an expression is expected. For example:

int[] x;
x = { 1, 2, 3 }; 

is not legal.

It's just an odd corner case of the C# language. There's no deeper meaning to the inconsistency you've discovered.

like image 174
Eric Lippert Avatar answered Jan 13 '23 00:01

Eric Lippert