Greg Greg - 1 month ago 14
C# Question

Can extension methods be applied to interfaces?

Is it possible to apply an extension method to an interface? (C# question)

That is for example to achieve the following:


  1. create an ITopology interface

  2. create an extension method for this interface (e.g. public static int CountNodes(this ITopology topologyIf) )

  3. then when creating a class (e.g. MyGraph) which implements ITopology, then it would automatically have the Count Nodes extension.



This way the classes implementing the interface would not have to have a set class name to align with what was defined in the extension method.

Answer

Of course they can; most of Linq is built around interface extension methods.

Interfaces were actually one of the driving forces for the development of extension methods; since they can't implement any of their own functionality, extension methods are the easiest way of associating actual code with interface definitions.

See the Enumerable class for a whole collection of extension methods built around IEnumerable<T>. To implement one, it's the same as implementing one for a class:

public static class TopologyExtensions
{
    public static void CountNodes(this ITopology topology)
    {
        // ...
    }
}

There's nothing particularly different about extension methods as far as interfaces are concerned; an extension method is just a static method that the compiler applies some syntactic sugar to to make it look like the method is part of the target type.