Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to use C# methods directly as delegates?

This is more of a C# syntax question rather than an actual problem that needs solving. Say I have a method that takes a delegate as parameter. Let's say I have the following methods defined:

void TakeSomeDelegates(Action<int> action, Func<float, Foo, Bar, string> func)
{
    // Do something exciting
}

void FirstAction(int arg) { /* something */ }

string SecondFunc(float one, Foo two, Bar three){ /* etc */ }

Now if I want to call TakeSomeDelegates with FirstAction and SecondFunc as arguments, As far as I can tell, I need to do something like this:

TakeSomeDelegates(x => FirstAction(x), (x,y,z) => SecondFunc(x,y,z));

But is there a more convenient way to use a method that fits the required delegate signature without writing a lambda? Ideally something like TakeSomeDelegates(FirstAction, SecondFunc), although obviously that doesn't compile.

like image 359
guhou Avatar asked Jul 10 '10 07:07

guhou


1 Answers

What you're looking for is something called 'method groups'. With these, you can replace one line lamdas, such as:

was:

TakeSomeDelegates(x => firstAction(x), (x, y, z) => secondFunc(x, y, z));

after replacing with method groups:

TakeSomeDelegates(firstAction, secondFunc);
like image 116
Steve Dunn Avatar answered Sep 30 '22 04:09

Steve Dunn