How can I specify default values for method parameters in c#7 tuples?
You can specify a default as long as you are happy with default-initialisation of the int
components to zero:
public static (int x, int y) AddTuples(
(int x, int y) a = default((int, int)),
(int x, int y) b = default((int, int)))
{
return (a.x + b.x, a.y + b.y);
}
Unfortunately you can't provide specific default values for the tuple's components.
However, for your specific example (where you want to default to (0, 0)
) this seems sufficient.
[Addendum]
Another approach to this specific example is to use a params
array:
public static (int x, int y) AddTuples(params (int x, int y)[] tuples)
{
return (tuples.Sum(t => t.x), tuples.Sum(t => t.y));
}
And then you can do:
Console.WriteLine($"Result is: {AddTuples()}"); // (0, 0)
Console.WriteLine($"Result is: {AddTuples((1, 1))}"); // (1, 1)
Console.WriteLine($"Result is: {AddTuples((1, 1), (2, 2))}"); // (3, 3)
Console.WriteLine($"Result is: {AddTuples((1, 1), (2, 2), (3, 3))}"); // (6, 6)
a
and b
are not constants. Everything that creates a new instance (whether it is a struct or a class) is not considered a constant, and method signatures only allow constants as default values.
That said, there is no way to default tuples from the method signature, you have to create a separate method.
The only way out seems to be using nullable arguments:
(int x, int y) AddTuples2((int x, int y)? a = null, (int x, int y)? b = null)
{
(int x, int y) aNN = a ?? (0,0);
(int x, int y) bNN = b ?? (0,0);
return (aNN.x + bNN.x, aNN.y + bNN.y);
}