This question already has an answer here:
This is a simple example of two extension methods overloads
public static class Extended
{
public static IEnumerable<int> Even(this List<int> numbers)
{
return numbers.Where(num=> num % 2 == 0);
}
public static IEnumerable<int> Even(this List<int> numbers, Predicate<int> predicate)
{
return numbers.Where(num=> num % 2 == 0 && predicate(num));
}
}
I'd like to be able to merge them into one, by setting a delegate to be optional:
public static class Extended
{
public static IEnumerable<int> Even(this List<int> numbers, Predicate<in> predicate = alwaysTrue)
{
return numbers.Where(num=> num % 2 == 0 && predicate(num));
}
public static bool alwaysTrue(int a) { return true; }
}
However, compiler throws an error:
Default parameter value for 'predicate' must be a compile-time constant
I don't see how my alwaysTrue function is not constant, but hey, compiler knows better :)
Is there any way to make the delegate parameter optional?
You could use a
null
-default value:It's not constant because you've created a delegate from a method group... that's not a compile-time constant as far as the C# language is concerned.
If you don't mind abusing the meaning of
null
slightly you could use:(You could still make
AlwaysTrue
a method and use a method group conversion, but the above approach is very slightly more efficient by creating the delegate instance just once.)What you have to do is allow it to be
null
, and then treat that as always true.You have two options for this, double the code to leave out the delegate call, this will perform faster in the cases where you don't pass the delegate.
Or, provide a dummy implementation as you wanted:
Also, consider whether you really want to do this. The effect optional parameters have on compiled code is that the calling code now provides the default value, which means it will always call the overload which take a list and a delegate.
If you later on want to go back, you need to ensure all code that calls the method is recompiled, since it won't magically start using the method that doesn't provide a delegate.
In other words, this call:
Will look like it was written like this:
If you now change the method to be overloaded yet again, if the above call isn't recompiled, then it will always call the one with a delegate, just providing
null
for that parameter.