Praesagus
Praesagus

Reputation: 2094

Pass a method as an argument

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;
}

Upvotes: 7

Views: 5410

Answers (5)

Jeff Yates
Jeff Yates

Reputation: 62367

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;
}

Upvotes: 13

Raghav
Raghav

Reputation: 9630

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;
}

Upvotes: 0

Amy B
Amy B

Reputation: 110071

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.

Upvotes: 4

Mark Rushakoff
Mark Rushakoff

Reputation: 258128

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;
}

Upvotes: 9

Related Questions