Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# referencing methods through variables?

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

like image 594
Oztaco Avatar asked Feb 16 '26 16:02

Oztaco


1 Answers

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.

like image 130
M.Babcock Avatar answered Feb 18 '26 05:02

M.Babcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!