Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<> as optional parameter of a function has to be a compile time constant? [duplicate]

Tags:

c#

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?

like image 430
krjw Avatar asked Jan 25 '23 23:01

krjw


2 Answers

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;

like image 78
Jonathon Chase Avatar answered Feb 07 '23 18:02

Jonathon Chase


An alternative to the answer from @JonathonChase is to use an overload:

private void func() => func(_ => true);
like image 23
Bill Tür stands with Ukraine Avatar answered Feb 07 '23 18:02

Bill Tür stands with Ukraine