29

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Babak.Abad
  • 2,839
  • 10
  • 40
  • 74
  • 1
    [C# Delegates, Anonymous Methods, and Lambda Expressions](http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-and-Lambda-Expressio) – I4V Aug 11 '13 at 21:29
  • 1
    Does this answer your question? [Pass Method as Parameter using C#](https://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – Davide Cannizzo Aug 23 '20 at 13:13

1 Answers1

44

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331