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#?
protecte
Delegates provide this mechanism. A quick way to do this in C# 3.0 for your example would be to use FuncTResult
is string
and lambdas.
Your code would then become:
protected void MyMethod(){
RunMethod(() => ParamMethod("World"));
}
protected void RunMethod(Func 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;
}