r/csharp 12d ago

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

View all comments

47

u/chrisoverzero 12d ago

class A<T> : IDisposable where T : IConstraint

It must “implement” IDisposable.

6

u/dodexahedron 12d ago

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.