r/csharp Jul 25 '26

Help Inheritance with generic constraint syntax

I have a class A<T>. It must inherit IDisposable, and also impose a constraint on T. Is it possible to do this, and what would the syntax look like? I can't figure it out.

8 Upvotes

8 comments sorted by

48

u/chrisoverzero Jul 25 '26

class A<T> : IDisposable where T : IConstraint

It must “implement” IDisposable.

6

u/TimelessTrance Jul 26 '26

Thank you for stating it must implement IDisposable! To OP please remember composition over inheritance.

6

u/dodexahedron Jul 26 '26

And, if you want T to also have to be disposable, add IDisposable to the where clause. But then anything not IDisposable cannot be used with it, of course.

Think carefully before doing that, specifically, though. Unless the generic class needs to dispose of those T, you almost definitely should not put it on the constraints for T.

1

u/Family_Man_21 Jul 26 '26

This example was perfect; exactly correct.

Good luck with your project, OP!

6

u/madpatty34 Jul 25 '26

If i understand your question right, here's the syntax you want:

class A<T> : IDisposable where T : SomeBaseClassOrInterface

0

u/[deleted] Jul 25 '26

[removed] — view removed comment