Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as parameter [duplicate]

Tags:

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?

like image 567
Babak.Abad Avatar asked Aug 11 '13 21:08

Babak.Abad


People also ask

Is it good practice to pass a function as a parameter?

Passing a private function to someone else because you specifically want them to call it in the way they document for that parameter, is absolutely fine.

How do you pass a function as a parameter?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

Does pass by value copy?

By definition, pass by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter. Use pass by value when when you are only "using" the parameter for some computation, not changing it for the client program.

What are two methods of parameter passing to function?

Passing Parameter to a Function: In C Programming we have different ways of parameter passing schemes such as Call by Value and Call by Reference.


1 Answers

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.

like image 175
p.s.w.g Avatar answered Nov 11 '22 23:11

p.s.w.g