Search code examples
c#genericsinterfaceextension-methods

c# extension method for a generic class with interface as type constraint


Is it possible in c# - and if so how - to extend a generic class but only if the generic type parameter implements a special interface?

For example something like this:

public static void SomeMethod(
    this SomeClass<ISomeInterface> obj, ISomeInterface objParam)
{
    ...
}

Solution

  • Yes, this can be done by making the method generic and adding a generic type constraint to the method, as follows:

    public static void SomeMethod<T>(
        this SomeClass<T> obj, ISomeInterface objParam)
        where T : ISomeInterface // <-- generic type constraint
    {
        ...
    }