What is the method group?

Asked

Viewed 751 times

12

Coding in C# I ended up making a mistake, perhaps by familiarity with other languages that I usually work, and forgot the parentheses.

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

I got the following mistake:

cannot Convert from 'method group' to 'Object'

I’ve even been researching what this is method group, but since it’s a concept I’ve never seen in any other language I haven’t fully understood its purpose, or why it exists.

1 answer

8


I don’t know if you understand that the methods already 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 created to facilitate the use of delegates, and consequently the events, so any of the methods can be directly associated with the delegate. Then Amble were also benefited.

If the method parameter Concat() hypothetically expected a delegate, so it would work. Of course, it wouldn’t make sense.

ToString() is a method, ToString It’s a group of methods, so it’s two very different things. There is language that is just a simplification of syntax for not existing this new concept.

Everywhere you accept a delegate you can create it in various 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 signature of the delegate the referenced method, in case the WriteLine(), with the equivalent signature will be called.

Using as 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");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If you’re curious to read the language specification, has very detailed information of how it works, this chapter is a very short text :P

  • And what would be the delegate on those lines?

  • 1

    Ah, is the Func<> and Action<>. These are types that facilitate the declaration of delegates. Otherwise it would have to declare them in another place for use, becomes impractical. This has existed since C# 3. You can see more in http://answall.com/q/90058/101

Browser other questions tagged

You are not signed in. Login or sign up in order to post.