Reputation: 642
Here's the code:
int[,] Arr;
Arr = Array.Empty();
And here's the compile error for the second line:
Error CS0411 The type arguments for method 'Array.Empty()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
This should be a simple syntax fix, but I haven't been able to get it.
Upvotes: 2
Views: 5341
Reputation: 19641
You may use:
int[,] Arr = new int[0, 0];
Or if you'd like to replicate the Empty()
method for multidimensional arrays, you could write a helper class for that:
static class MultiDimArray
{
public static T[,] Empty2D<T>() => new T[0, 0];
public static T[,,] Empty3D<T>() => new T[0, 0, 0];
// Etc.
}
Usage:
int[,] Arr = MultiDimArray.Empty2D<int>();
To take this a step further (and actually make it useful), we can make this work exactly like Array.Empty()
, and thus avoid unnecessary memory allocation by using static readonly fields so that they're only initialized once:
static class MultiDimArray
{
public static T[,] Empty2D<T>() => Empty2DArray<T>.Value;
public static T[,,] Empty3D<T>() => Empty3DArray<T>.Value;
// Etc.
private class Empty2DArray<T> { public static readonly T[,] Value = new T[0, 0]; }
private class Empty3DArray<T> { public static readonly T[,,] Value = new T[0, 0, 0]; }
// Etc.
}
Upvotes: 6