views:

4939

answers:

4

I have often encountered an error such as "cannot convert from 'method group' to 'string'" in cases like :

var list = new List<string>();
// ... snip
list.Add(someObject.ToString);

of course there was a typo in the last line because I forgot the round paranthesis after "ToString". The correct form would be :

var list = new List<string>();
// ... snip
list.Add(someObject.ToString()); // <- notice the paranthesis

However I came to wonder what is a method group. Google isn't much of a help and MSDN neither.

+21  A: 

A method group is the name for a set of methods (that might be just one) - i.e. in theory the 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 brackets, again; overload resolution kicks in and you have unambiguously identified a method call.

Marc Gravell
What would be typical uses of a method group? Since (so I understand) it has the same name the parameter count and/or types will differ. So you cannot invoke more than one method from the method group using the group.
Andrei Rinea
It is purely a compiler term for "I know what the method name is, but I don't know the signature"; it has no existence at runtime. AFAIK, the only use of a method-group *by itself* (no brackets etc) is during delegate construction.
Marc Gravell
ECMA 334v4 §14.1: A method group can be used in an invocation-expression (§14.5.5), used in a delegate-creation-expression (§14.5.10.3), or implicitly converted to a compatible delegate type. In any other context, an expression classified as a method group causes a compile-time error.
Marc Gravell
Thank you! _
Andrei Rinea
+2  A: 

The first result in your MSDN search said

The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke

my understanding is that basically because when you just write someInteger.ToString, it may refer to

Int32.ToString(IFormatProvider)

or it can refer to

Int32.ToString()

so it is called a method group

oykuo
+2  A: 

The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.

1800 INFORMATION
+1  A: 

Also, if you are using linq, you can apparently do something like myList.select(methodGroup);

So, for example, i have

private string DoSomethingToMyString(string input){ //blah blah }

public list GetStringStuff(){ return something.getStringsFromSomewhere.select(DoSomethingToMyString); }

Kaeles
Thanks!!!!!!!!!
Andrei Rinea