CloudCuckooHome
CloudCuckooHome

Reputation: 39

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

Upvotes: 0

Views: 670

Answers (1)

Steven
Steven

Reputation: 172606

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

Upvotes: 1

Related Questions