How do I pass a method as an argument? I do this all the time in Javascript and need to use anonymous methods to pass params. How do I do it in c#?
protected void MyMethod(){
RunMethod(ParamMethod("World"));
}
protected void RunMethod(ArgMethod){
MessageBox.Show(ArgMethod());
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .
Pass a Method as a Parameter by Using the lambda Function in Java. This is a simple example of lambda, where we are using it to iterate the ArrayList elements. Notice that we're passing the lambda function to the forEach() method of the Iterable interface. The ArrayList class implements the Iterable interface.
Methods are passed as arguments just like a variable. In this example, we define a class and its objects. We create an object to call the class methods. Now, to call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name.
@rupinderjeet47 Yes. In class A , methodToPass() take an int as it's argument.
Delegates provide this mechanism. A quick way to do this in C# 3.0 for your example would be to use Func<TResult>
where TResult
is string
and lambdas.
Your code would then become:
protected void MyMethod(){
RunMethod(() => ParamMethod("World"));
}
protected void RunMethod(Func<string> method){
MessageBox.Show(method());
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
However, if you are using C#2.0, you could use an anonymous delegate instead:
// Declare a delegate for the method we're passing.
delegate string MyDelegateType();
protected void MyMethod(){
RunMethod(delegate
{
return ParamMethod("World");
});
}
protected void RunMethod(MyDelegateType method){
MessageBox.Show(method());
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
Your ParamMethod is of type Func<String,String> because it takes one string argument and returns a string (note that the last item in the angled brackets is the return type).
So in this case, your code would become something like this:
protected void MyMethod(){
RunMethod(ParamMethod, "World");
}
protected void RunMethod(Func<String,String> ArgMethod, String s){
MessageBox.Show(ArgMethod(s));
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
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