So I have the following function. I would like it to have a standard parameter value but I can't get it to work as it needs to be a compile time constant. I know I can set it to null but I want it to be a specific function.
private void func(Func<List<int>, bool> eval = _ => true)
{
var b = eval();
}
Is it even possible to something like this?
Since default parameters must be compile time constants, you can't provide an easy default function quite like you want. You can work around this, though, using null as you pointed out.
private void func(Func<List<int>, bool> eval = null)
{
eval = eval ?? (_ => true);
// Do things.
}
This will assign your default implementation if null is passed, or the function is called without any parameters.
In modern versions of C#, you can use the null assignment operator, ??=
.
This would look something like this:
eval ??= _ => true;
An alternative to the answer from @JonathonChase is to use an overload:
private void func() => func(_ => true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With