3

Lets say i have a method

public static void Blah(object MyMethod) { // i dont know what to replace object with
MyMethod; // or however you would use the variable
}

so basically i need to be able to reference a method through a variable

Oztaco
  • 3,399
  • 11
  • 45
  • 84
  • possible duplicate of [Pass Method as Parameter using C#](http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – M.Babcock Mar 12 '12 at 01:35

2 Answers2

6

You're looking for a delegate.

public delegate void SomeMethodDelegate();

public void DoSomething()
{
    // Do something special
}

public void UseDoSomething(SomeMethodDelegate d)
{
    d();
}

Usage:

UseDoSomething(DoSomething);

Or using lambda syntax (if DoSomething was a Hello World):

UseDoSomething(() => Console.WriteLine("Hello World"));

There is also shortcut syntax available for Delegates in the form of Action and Func types:

public void UseDoSomething(Action d)

And if you need to return a value from your delegate(like an int in my example) you can use:

public void UseDoSomething2(Func<int> d)

NOTE: Action and Func provide generic overloads that allow parameters to be passed.

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
4

The .Net framework has a bunch of delegate types built-in which make this easier. So if MyMethod takes a string parameter you could do this:

public static void Blah(Action<string> MyMethod) { 
    MyMethod; 
} 

if it takes two ints and returns a long you would do:

public static void Blah(Func<int, int, long> MyMethod) { 
    MyMethod; 
} 

There are versions of Action<> and Func<> with varying number of type parameters which you can specify as required.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116