C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Extension delegates

Chapter 10: Extension methods: 10.2

Created: 3/15/2008
Last updated: 3/15/2008

There's one feature I wasn't even aware of when writing the book. I only found out about it when reading the preview of another C# 3 book by Bruce Eckel and Jamie King.

Basically, the feature allows you to specify an extension method as a method group using extension syntax. It can then be converted to a delegate of an appropriate type as if it were an instance method. As an example, take the Count() extension method on IEnumerable<T>. The actual declared method is static and takes a single parameter, so in some ways we shouldn't logically be able to use it as a the target of an Func<int> delegate which takes no parameters and returns an int, right? Nope...

using System;
using System.Linq;

public class Test
{
    static void Main()
    {
        string[] x = {"a""b""c"};
        
        // Call extension method directly
        Console.WriteLine(x.Count());
        
        // Convert extension method group to delegate
        Func<int> func = x.Count;
        
        // Print out the target of the delegate
        Console.WriteLine(func.Target);
        
        // Print out the value returned by calling the delegate
        Console.WriteLine(func());
    }
}

This compiles and executes, with this output:

3
System.String[]
3

Note how the target of the delegate is the array, even though delegates which use static methods normally have a null target.

Basically, the long and the short of it is that extension methods can be used as if they were instance methods, not just for calling, but also for conversion into delegates. That's really neat.