raklos raklos - 2 months ago 5
C# Question

Pass a method as a parameter

I want to be able to pass a method as a parameter.

eg..

//really dodgy code
public void PassMeAMethod(string text, Method method)
{
DoSomething(text);
// call the method
//method1();
Foo();
}

public void methodA()
{
//Do stuff
}


public void methodB()
{
//Do stuff
}

public void Test()
{
PassMeAMethod("calling methodA", methodA)
PassMeAMethod("calling methodB", methodB)
}


How can I do this?

Answer

You need to use a delegate, which is a special class that represents a method. You can either define your own delegate or use one of the built in ones, but the signature of the delegate must match the method you want to pass.

Defining your own:

public delegate int MyDelegate(Object a);

This example matches a method that returns an integer and takes an object reference as a parameter.

In your example, both methodA and methodB take no parameters have return void, so we can use the built in Action delegate class.

Here is your example modified:

public void PassMeAMethod(string text, Action method)
{
  DoSomething(text);
  // call the method
  method();    
}

public void methodA()
{
//Do stuff
}


public void methodB()
{
//Do stuff
}

public void Test()
{
//Explicit
PassMeAMethod("calling methodA", new Action(methodA));
//Implicit
PassMeAMethod("calling methodB", methodB);

}

As you can see, you can either use the delegate type explicitly or implicitly, whichever suits you.

Comments