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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With