What is method group

Method group is an interesting way to enhance code clarity. Let’s look at code below which uses the method group.

List<string> words = new List<string> { "apple", "orange", "pear" };

words.ForEach(Console.WriteLine);
apple
orange
pear

How its work

As we see that code somehow display words on console. Method group allows us to enter only the name of the method, so we can treat it as a delegate variable. So let’s see how the ForEach method declaration looks like.

public void ForEach(Action<T> action)

As we see method requires action parameter which is simple generic delegate:

delegate void Action<in T>(T obj);

So the ForEach method looks for delegate, and in code we provide it just typing Console.WriteLine. As you know the WriteLine method have got many overloads. So if you just type Console.WriteLine the compiler have to fit in the right method, in our example it will be WriteLine(String), because we use List<string>.

WriteLine()
WriteLine(Boolean)
WriteLine(Char)
WriteLine(Char[])
WriteLine(Decimal)
WriteLine(Double)
WriteLine(Int32)
WriteLine(Int64)
WriteLine(Object)
WriteLine(Single)
WriteLine(String)
WriteLine(UInt32)
WriteLine(UInt64)
WriteLine(String, Object)
WriteLine(String, Object[])
WriteLine(Char[], Int32, Int32)
WriteLine(String, Object, Object)
WriteLine(String, Object, Object, Object)
WriteLine(String, Object, Object, Object, Object)

Custom class example

To better understand method group below there is a code describing the phenomenon based on custom class.

public static void Main()
{
    MethodGroup methodGroup = new MethodGroup();
    methodGroup.Foreach(Display);
}

static void Display (string text)
{
    Console.WriteLine(text);
}

class MethodGroup
{
    private string[] wegetables = { "apple", "orange", "pear" };

    public delegate void Method<in T>(T obj);

    public void Foreach(Method<string> action)
    {
        foreach (string wegetable in wegetables)
            action.Invoke(wegetable);
    }
}
apple
orange
pear

Using advantages

That method can really enhance code clarity. Otherwise we are forced to use one of other possibilities:

  • anonymous method:
    words.Foreach(delegate(string word)
                            {
                                Console.WriteLine(word);
                            });
    
  • lambda expression:
    words.ForEach(word => Console.WriteLine(word));