C # method references via variables?
You are looking for a delegate .
public delegate void SomeMethodDelegate();
public void DoSomething()
{
// Do something special
}
public void UseDoSomething(SomeMethodDelegate d)
{
d();
}
Using:
UseDoSomething(DoSomething);
Or using lambda syntax (if there DoSomething
was Hello World):
UseDoSomething(() => Console.WriteLine("Hello World"));
For delegates, shortcut syntax is also available in the form Action
and Func
:
public void UseDoSomething(Action d)
And if you need to return a value from your delegate (for example int
in my example), you can use:
public void UseDoSomething2(Func<int> d)
NOTE: Action and Func provide generic overloads that allow you to pass parameters.
source to share
The .NET framework has a bunch of built-in delegate types that make this easier. So if it MyMethod
takes a parameter string
, you can do this:
public static void Blah(Action<string> MyMethod) {
MyMethod;
}
if it takes two int
and returns long
:
public static void Blah(Func<int, int, long> MyMethod) {
MyMethod;
}
There are versions Action<>
and Func<>
with different numbers of type parameters that you can specify as needed.
source to share