Search code examples
c#funcactionmethod

How can i call a Func<int,int,int> arguments in a method in C#?


I am trying to create a method which accepts different methods(Funcs) as a parameter.
I have a small problem in defining the Funcs arguments. Suppose i need to call some thing like this :

public static void SomeTestMethod(int number,string str)
{
    Check(MethodOne(number,str));
}

And For Check i have this:

public static int Check(Func<int,string,int> method)
{
         // some conditions 
      method(where should i get the arguments ?);
}

Now my question is how should i set the needed arguments? I feel providing separate arguments for Check, is not elegant, since i need to call Check with the signature i provided in the TestMethod.
I dont want to have

Check(MethodOne,arg1,arg2,etc));  

If it is possible i need to provide this signature instead:

Check(MethodOne(number,str));

Solution

  • I think you want this:

    public static void SomeTestMethod(int number,string str)
    {
        Check( () => MethodOne(number,str));
    }
    
    public static int Check(Func<int> method)
    {
             // some conditions 
          return method();
    }