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;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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;
}
Method 2
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;
}
Method 3
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
Method 4
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.
Method 5
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;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0