Alex Rivera | Logout

Method Groups (C# In Depth) - Need help understanding better what a Method Group is

Asked 2011-01-21T15:12:01.473
10

So I have read a number of StackOverflow questions related to "what is a method group" as well as other internet articles, they all say the same thing in the bottom line - that a method group is "a group of overloaded methods".

However, reading Jon Skeet's "C# In Depth (second edition)", he states the following verbiage regarding method group in the context of Lambda expressions (chapter 9.4.1)

Reasons for change: streamlining generic method calls

Type inference occurs in a few situations. We’ve already seen it apply to implicitly typed arrays, and it’s also required when you try to implicitly convert a method group to a delegate type. This can be particularly confusing when the conversion occurs when you’re using a method group as an argument to another method: with overloading of the method being called, and overloading of methods within the method group, and the possibility of generic methods getting involved, the set of potential conversions may be enormous."

Either method groups are allot more than just a group of overloaded methods, or he saying you can actually create a delegate that retains an entire method group. Or something entirely different that I am not quite grasping.

Can someone explain what he is stating is possible here?

Thanks,

c#
Edit
Report

1 Answer

15

The scenario that Jon is describing is this one:

int M() {...}
string M<T>(T t) {...}
double M<T>(List<T> t) {...} 
static void M(double d) {...}
... etc ...

void N(Func<int> f) {...}
void N<T>(Action<T> a) {...}
void N<T>(Func<IEnumerable<T>> f) {...}
... etc ...

N(M);

N and M are both method groups, containing potentially dozens of methods, some that might be generic. The problem posed to the compiler is "work out which methods N and M are the ones that the developer intended, and work out the type arguments if the intended method is generic".

To work all that out the compiler has to try every possible N, and then figure out which of every possible M is compatible with the delegate type of the formal parameter of that overload of N. It has to discard the ones that don't work, and then from all those potentially hundreds or thousands of combinations left, figure out which one is the "best", if any. This is a somewhat tricky problem in semantic analysis.

answered 2011-01-21T16:02:23.577

Your Answer