I need a way to define a method in c# like this:
public String myMethod(Function f1,Function f2)
{
//code
}
Let f1 is:
public String f1(String s1, String s2)
{
//code
}
is there any way to do this?
I need a way to define a method in c# like this:
public String myMethod(Function f1,Function f2)
{
//code
}
Let f1 is:
public String f1(String s1, String s2)
{
//code
}
is there any way to do this?
Sure you can use the Func<T1, T2, TResult>
delegate:
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
}
This delegate defines a function which takes two string parameters and return a string. It has numerous cousins to define functions which take different numbers of parameters. To call myMethod
with another method, you can simply pass in the name of the method, for example:
public String doSomething(String s1, String s2) { ... }
public String doSomethingElse(String s1, String s2) { ... }
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
string result1 = f1("foo", "bar");
string result2 = f2("bar", "baz");
//code
}
...
myMethod(doSomething, doSomethingElse);
Of course, if the parameter and return types of f2
aren't exactly the same, you may need to adjust the method signature accordingly.