Reputation: 7267
Currently I am doing this
public int[][] SomeMethod()
{
if (SomeCondition)
{
var result = new int[0][];
result[0] = new int[0];
return result;
}
// Other code,
}
Now in this I only want to return empty jagged array of [0][0]. Is it possible to reduce three lines to one. I want to achieve something like this
public int[][] SomeMethod()
{
if (SomeCondition)
{
return new int[0][0];
}
// Other code,
}
Is it possible?
Upvotes: 1
Views: 2765
Reputation: 1089
In the general case, you can let the compiler count elements for you:
public int[][] JaggedInts()
{
return new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
}
Or if you want it very compact, use an expression body:
public int[][] JaggedInts() => new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
Since you asked for an empty jagged array, you already had it:
var result = new int[0][];
The next line in your question will throw a run-time exception, since [0] is the first element in an array, which must be 1 or or more elements in length;
result[0] = new int[0]; // thows IndexOutOfRangeException: Index was outside the bounds of the array.
Here is what I think you asked for in just one line:
public int[][] Empty() => new int[0][];
Upvotes: 2
Reputation: 59906
by returning value of jagged array its give you some ambiguous result,if you want to return some specific value of some specific index of jagged array you can return by assigning them to variable
public static int aaa()
{
int[][] a = new int[2][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
int abbb=a[0][0];
Console.WriteLine(a[0][0]);
return abbb;
}
the following code will return 1 becoz this is first element of jagged array
Upvotes: 0
Reputation: 8404
Please have a look here https://stackoverflow.com/a/1739058/586754 and below.
You will need to create some helper functions and then it becomes a one-liner.
(Also was looking for a 1-line-solution.)
Upvotes: 0