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 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;
}
protected String ParamMethod(String sWho)
{
return "Hello " + sWho;
}
protected void RunMethod(Func<string> ArgMethod)
{
MessageBox.Show(ArgMethod());
}
protected void MyMethod()
{
RunMethod( () => ParamMethod("World"));
}
That () =>
is important. It creates an anonymous Func<string>
from the Func<string, string>
that is ParamMethod.
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;
}
protected delegate String MyDelegate(String str);
protected void MyMethod()
{
MyDelegate del1 = new MyDelegate(ParamMethod);
RunMethod(del1, "World");
}
protected void RunMethod(MyDelegate mydelegate, String s)
{
MessageBox.Show(mydelegate(s) );
}
protected String ParamMethod(String sWho)
{
return "Hello " + sWho;
}
Take a look at C# Delegates
http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx
Tutorial http://www.switchonthecode.com/tutorials/csharp-tutorial-the-built-in-generic-delegate-declarations