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

Time:07-15

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)
{
    ...
}

CodePudding user response:

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
{
    ...
}
  • Related