Search code examples
c#.netdispose

Order of disposal for base classes


When a derived class overrides Dispose should the base class Dipose be called first before the derived class disposes of any local resources?

The reason I ask is because someone on our team is saying yes for every scenario, I'm trying to work out if this is good idea or just 'cargo cult' programming, I don't have a strong view either way.

Before:

 public override void Dispose()
 {
     base.Dispose();

     if (!_isDisposed)
     {
         _isDisposed = true;

         if (_foo != null)
         {
             _foo.Dispose();
         }
     }
 }

After:

 public override void Dispose()
 {
     if (!_isDisposed)
     {
         _isDisposed = true;

         if (_foo != null)
         {
             _foo.Dispose();
         }
     }

     base.Dispose();
 }

Note: I'm not looking for how to implement the basic dispose pattern but more clarification from peoples experiences.


Solution

  • "It depends"

    You can't have a hard-and-fast rule for this, because the order you need to call dispose will depend on the implementation of the classes.

    Sometimes you might want it at the start, sometimes at the end, and sometimes in the middle. Most of the time, it probably won't matter.

    Generally speaking, people seem to call it first (in the absence of any other reason to call it at a different time).

    One reason to lean towards calling it first is that then the derived class has a chance to do special stuff afterwards if it needs to.