Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
{
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading