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:
create an ITopology interface
create an extension method for this interface (e.g. public static int CountNodes(this ITopology topologyIf) )
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.
Solution 1:
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.