Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a method group in C#?

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 invocation parentheses after ToString. The correct form would be:

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

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

like image 632
Andrei Rînea Avatar asked May 20 '09 08:05

Andrei Rînea


2 Answers

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 parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

like image 142
Marc Gravell Avatar answered Sep 30 '22 23:09

Marc Gravell


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 } 

Instead of explicitly stating the variable to be used like this:

public List<string> GetStringStuff() {     return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str)); } 

I can just omit the name of the var:

public List<string> GetStringStuff() {     return something.getStringsFromSomewhere.Select(DoSomethingToMyString); } 
like image 34
Kaeles Avatar answered Sep 30 '22 21:09

Kaeles