patterncsharpCritical
What is a method group in C#?
Viewed 0 times
groupwhatmethod
Problem
I have often encountered an error such as "cannot convert from 'method group' to 'string'" in cases like:
of course there was a typo in the last line because I forgot the invocation parentheses after
However I came to wonder what is a method group. Google isn't much of a help nor MSDN.
var list = new List();
// ... snip
list.Add(someObject.ToString);of course there was a typo in the last line because I forgot the invocation parentheses after
ToString. The correct form would be:var list = new List();
// ... snip
list.Add(someObject.ToString()); // <- notice the parenthesesHowever I came to wonder what is a method group. Google isn't much of a help nor MSDN.
Solution
A method group is the name for a set of methods (that might be just one) - i.e. in theory the
It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.
Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.
Links
ToString method may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc - hence ToString by itself is a "method group".It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.
Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.
Links
- Method group conversions
Context
Stack Overflow Q#886822, score: 391
Revisions (0)
No revisions yet.