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
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
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.
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 int
s 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.