Given a list of objects to be passed to a method with overloads, I want to determine what overload best matches the object types in order to invoke that method.
string TheMethod(string? foo, string? bar); // one overload
string TheMethod(string? foo); // another overload
List<object?> arguments = [...];
switch (arguments)
{
case [string foo, string bar]:
return TheMethod(foo, bar);
case [string foo]:
return TheMethod(foo);
}
This works fine when all arguments are non-null, however, I need to account for the possibility of null values. Other polymorphic types doesn't seem to have this problem.
Is there a way to write patterns such that I can match values that are assignable to the type (specifically for null)?
There are convoluted ways I could write it to allow for the possibility of null values, but that's not fun:
switch (arguments)
{
case [var foo, var bar] when (foo is null or string && bar is null or string):
return TheMethod(foo as string, bar as string);
...
case [string? foo, string? bar]: // this would be nice, but illegal
}
Is this the best we can do currently?
null
value in that position would be selected. If there was a tiebreaker situation where multiple overloads match, will probably throw an error.