2

This declaration causes an error because the last item is empty.

  var foo = new[] {
                 new [] {1, 2, 3},
                 new [] {3, 4, 5},
                 new [] {}
                 };

I understand that in general the compiler would need all these arrays to be of the same (anonymous) type, but it seems like it should allow "empty" as a special case and type it like all the others.

Is there some way to declare the above so that I can have an empty array along with the non-empty ones?

Michael

Michael Ray Lovett
  • 6,668
  • 7
  • 27
  • 36

5 Answers5

7
new [] {1, 2, 3}

is shorthand for

new int[] { 1,2,3 }

The compiler can figure out it has to be int because the array contains ints.
But if you say

new [] { }

since the array is empty, the Type cannot be determined. So you have to explicitly tell the compiler what the Type is:

var foo = new[] {
             new [] {1, 2, 3},
             new [] {3, 4, 5},
             new int [] {}
             };
Dennis_E
  • 8,751
  • 23
  • 29
5

Sure, just make it an int[]:

int[][] foo = new[] {
         new [] {1, 2, 3},
         new [] {3, 4, 5},
         new int[] {}
};
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You can if you iniltialise to a specific type:

        var foo = new int[][] {
             new int[] {1, 2, 3},
             new int[] {3, 4, 5},
             new int[] {}
             };
James Dev
  • 2,979
  • 1
  • 11
  • 16
0

Creating an empty array implicitly is not possible. As @Dennis_E said "since the array is empty, the Type cannot be determined. "

You can refer to All possible C# array initialization syntaxes

Quoting from related part:

Empty arrays

...
var data8 = new [] { } and int[] data9 = new [] { } are not compilable.
...

And maybe to this MSDN article -which gives less details btw-

Community
  • 1
  • 1
uTeisT
  • 2,256
  • 14
  • 26
0

if you dont wanna explicitly write the type, you can use linq to filter the last array

var foo = new [] {
    new [] {1, 2, 3},
    new [] {3, 4, 5},
    new [] {0}.Where(e => false).ToArray()
};

this way it would work event if you has to change this code to:

var foo = new[] {
    new [] { new { N = 1 }, new { N = 2 }, new { N = 3} },
    new [] { new { N = 3 }, new { N = 4 }, new { N = 5} },
    new [] { new { N = 0 } }.Where(e => false).ToArray()
};
lmcarreiro
  • 5,312
  • 7
  • 36
  • 63