Implementing IDisposable on a subclass when the parent also implements IDisposable

后端 未结 5 1932
無奈伤痛
無奈伤痛 2020-12-01 08:03

I have a parent and child class that both need to implement IDisposable. Where should virtual (and base.Dispose()?) calls come into p

5条回答
  •  执念已碎
    2020-12-01 08:37

    When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else.

    This is something you shouldn't be concerned with.

    When you subclass an IDisposable class, all of the "Dispose pattern" plumbing is already being handled for you by the base class. You really should do nothing but override the protected Dispose(bool) method, and track whether you've been disposed already (to properly raise ObjectDisposedException.)

    For details, see my blog post on Subclassing from an IDisposable class.


    Also, often, it's a good idea to consider encapsulating the IDisposable class instead of subclassing it. There are times when subclassing an IDisposable class is appropriate, but they are somewhat rare. Encapsulation is often a better alternative.

提交回复
热议问题