Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a method with default values to Func<> without those parameters?

I would like to be able to do the following:

Func<int,bool> tryMethodFunc = TryMethod;

Where TryMethod has a signature like:

bool TryMethod(int value, int value2 = 0, double value3 = 100.0)

I'm not opposed to breaking the method up into a curried format but that would be more work if there is a way to do this without that.

like image 203
Firestrand Avatar asked Dec 10 '12 16:12

Firestrand


1 Answers

Optional parameters is a language feature, the compiler is responsible for translating the calls to methods with optional parameters to full call with values.

Look at this simple piece of code below,

    public void GeneralMethod()
    {
        TestMethod(6);
    }

    public bool TestMethod(int a, int b = 8)
    {
        return true;
    }

When you disassemble these methods, you will see that the C# compiler actually replaced the call to TestMethod with one parameter to a call with both the parameters. The screen shot from ildasm proves that,

ildasm screen shot

Now, Coming to current problem, the line of code in question is trying to bind a Func with a method that has optional parameters. If C# compiler have to handle this, it has to ensure that the Func some knows the default values. While this could have been achieved by compiler, it completely defeats the purpose of Func.

Purpose of Func is to provides a way to store anonymous methods in a generalized and simple way." reference

Another similar question in stackoverflow can be found here

@Chris Sinclair's solution works around this by creating an anonymous method that takes one parameter and calls the TryMethod from the body of this anonymous method.

like image 93
humblelistener Avatar answered Oct 18 '22 14:10

humblelistener