0

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));
Hossein
  • 24,202
  • 35
  • 119
  • 224

2 Answers2

2

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();
}
Henrik
  • 23,186
  • 6
  • 42
  • 92
1
public static void Check<TReturnValue>(
                       Func<int, string, TReturnValue> method, 
                       int arg1, 
                       string arg2)
{
    method(arg1, arg2);
}

calling:

public static SomeClass MethodOne(int p1, string p2)
{
   // some body
}

Check(MethodOne, 20, "MyStr");

You have missed the type of return value (the last generic parameter means the type of return value). If you don't want to Func return anything, just use Action:

public static void Check(
                       Action<int, string> method, 
                       int arg1, 
                       string arg2)
{
    method(arg1, arg2);
}