Can extension methods be applied to interfaces?

C#.NetInterfaceExtension Methods

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregView Question on Stackoverflow
Solution 1 - C#AaronaughtView Answer on Stackoverflow