C# – Method inside generic class with additional constraints to T

  • A+

I have a generic class Foo<T> where T: SomeBaseType.

And in the specific case where T is SpecificDerivedType, I want my class to have an additional method.

Something like:

class Foo<T> where T: SomeBaseType {     //.... lots of regular methods taking T, outputting T, etc.      //in pseudo code     void SpecialMethod() visible if T: SpecificDerivedType     {         //...code...     } } 

How can I achieve this?

How can I achieve this?

You can't. Create a specialized Foo.

class SpecialFoo<T> : Foo<T> where T: SpecificDerivedType {     void SpecialMethod()     {         //...code...     } } 

Other suggest an extension method, which is obviously not the same as what you ask. It might be a workaround though.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: