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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With