Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can extension methods be applied to interfaces?

People also ask

Where do you put extension methods?

An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.

When it is useful to use extension methods?

One of the great reasons for using extension methods is LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure.

Can you add extension methods to an existing static class?

There's no way to add them currently because the feature doesn't exist in C#.

When should we use extension methods in C#?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.


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.