views:

88

answers:

4

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.

+1  A: 

The compiler will accept names of method groups where a delegate is needed, as long as it can figure out which overload to choose, you don't need to build a lambda. What is the exact compiler error message you're seeing?

Ben Voigt
Bear in mind that it can only figure out 'in' parameters, i.e. it can't resolve the type that a method returns: http://stackoverflow.com/questions/3203643/generic-methods-in-net-cannot-have-their-return-types-inferred-why
Steve Dunn
Since you can't overload method groups based on return type, this isn't a problem. (You can overload `operator implicit` and `operator explicit` on return type, but these can't be named as method groups).
Ben Voigt
+2  A: 

Just skip the parens on the function names.

        TakeSomeDelegates(FirstAction, SecondFunc);

EDIT:

FYI Since parens are optional in VB, they have to write this...

 TakeSomeDelegates(AddressOf FirstAction, AddressOf SecondFunc)
Jonathan Allen
+3  A: 

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);
Steve Dunn
thanks for this answer! I'm going to accept this because of the link explaining why this works :)
BleuM937
A: 

Yes it is called Method Group, and more precise example of that is...

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

static string SecondFunc(float one, Foo two, Bar three) { return ""; }


Action<int> act1 = FirstAction;
Func<float, Foo, Bar, string> act2 = SecondFunc;


TakeSomeDelegates(firstAction, secondFunc);

In this way you can use Method Group.

Samdrain