Question

Is there a point in securing myself against using a disposed class? I just cought myself on adding following two lines to all methods of my IDisposable class:

if (disposed)
    throw new InvalidOperationException("Attempt to use disposed object!");

That just doesn't seem right.

Was it helpful?

Solution

My best answer would be it depends.

Is the disposable class only used within a single project?

  • probably no (though an assert to the same effect might not be bad)

Is the class used by anyone outside of yourself or a small team?

  • probably yes

What are the side effects of accessing a disposed object?

  • if it will otherwise throw exceptions the above will make your life easier in debugging but the end result is the same in most cases
  • if it will work just fine (i.e. reallocate any necessary resources etc) then who cares really
  • if it will result in undefined or unpredictable behavior that DOESN'T throw exceptions then definately, especially if you answered no and then yes to the questions above

OTHER TIPS

I would suggest that what you have done is overkill. I agree with dkackman that you should probably do as you have for those members that could fail silently but not for all. You could just do as the Form class does and provide an IsDisposed property. It is then the developer's responsibility to check for themselves if they don't already know that the object is disposed or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top