What is the method group?

12

Coding in C # I ended up making a mistake, maybe because of familiarity with other languages I usually work with, and I forgot the parentheses.

string.Concat(numero.ToString, "A")

I received the following error:

  

can not convert from 'method group' to 'object'

I've even been researching what this method group is, but since it's a concept I've never seen in another language I did not fully understand its purpose, or why it exists.     

asked by anonymous 14.03.2017 / 13:13

1 answer

8

I do not know if you already understand that the methods have overloads ( signatures ) then as there are several methods with the same name, they form a group. Obviously the group can be formed by only one method if it has only one signature.

This was a very interesting idea originally designed to make it easier to use delegates, and consequently of events , so any of the methods can be associated with the delegate directly. Then lambdas have benefited as well.

If the method parameter Concat() hypothetically expected a delegate, then it would work. Of course that would not make sense.

ToString() is a method, ToString is a method group, so they are two very distinct things. It has language that is just a simplification of syntax because this new concept does not exist.

Everywhere I accept a delegate you can create it in several ways:

Action<string> x = delegate(string txt) { WriteLine(txt); };

This is the initial form of C # and is almost obsolete, replaced by:

Action<string> x = txt => WriteLine(txt);

Or you can use a method group :

Action<string> x = WriteLine;

According to the delegate's signature the referenced method, in this case the WriteLine() , with the equivalent signature will be called.

Using a delegate reference:

using System;
using static System.Console;

public class Program {
    public static void Main() {
        var numero = 123;
        Func<string, string> func = numero.ToString;
        WriteLine(func("000000"));
        Func<string> func2 = numero.ToString;
        WriteLine(func2());
        Action<string> a = delegate(string txt) { WriteLine(txt); };
        Action<string> b = txt => WriteLine(txt);
        Action<string> c = WriteLine;
        a("abc");
        b("abc");
        c("abc");
    }
}

See running on .NET Fiddle . And No Coding Ground . Also I put it in GitHub for future reference .

If you are curious about reading the language specification , you have detailed information on how it works, this chapter is a short text: P

    
14.03.2017 / 13:15