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;
}
Delegates provide this mechanism. A quick way to do this in C# 3.0 for your example would be to use
Func<TResult>whereTResultisstringand lambdas.Your code would then become:
However, if you are using C#2.0, you could use an anonymous delegate instead: