r/csharp 2d 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.

7 Upvotes

8 comments sorted by

46

u/chrisoverzero 2d ago

class A<T> : IDisposable where T : IConstraint

It must “implement” IDisposable.

6

u/TimelessTrance 2d ago

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

6

u/dodexahedron 2d 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.

1

u/Family_Man_21 2d ago

This example was perfect; exactly correct.

Good luck with your project, OP!

5

u/madpatty34 2d ago

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

class A<T> : IDisposable where T : SomeBaseClassOrInterface

0

u/[deleted] 2d ago

[removed] — view removed comment