C # method references via variables?

Let's 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 refer to the method using a variable

+3


source to share


2 answers


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.

+6


source


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.

+4


source







All Articles