Is there a method, or some other light-weight way, to check if a reference is to a disposed object?
P.S. - This is just a curiousity (sleep well, not in production code). Yes, I know I can catch the ObjectDisposedException
upon trying to access a member of the object.
I see this is old, but I did not see an answer. Some not all disposable objects like a DataSet have a disposed event you can attach.
There is nothing built in that will allow this. You would need to expose an IsDisposed boolean property that reflects an internal disposed flag.
It depends, there are
IDisposable
objects that allow to call theDispose
method as much as you want, and there areIDisposable
objects that throwObjectDisposedException
. In such a case these objects must track the state (usually implemented with a private boolean fieldisDisposed
).No - default implementation of IDisposable pattern does not support it
If it is not your class and it doesn't provide an IsDisposed property (or something similar - the name is just a convention), then you have no way of knowing.
But if it is your class and you are following the canonical IDisposable implementation, then just expose the _disposed or _isDisposed field as a property and check that.
The
Dispose
method is required to perform whatever cleanup will be required before an object is abandoned; if no cleanup is required, it is not required to do anything. Requiring an object to keep track of whether it has been disposed, even when theDispose
method would otherwise do nothing, would require manyIDisposable
objects to add a flag for very limited benefit.It might have been helpful if
IDisposable
included two properties--one which indicated whether an object needed disposing, and one of which indicated that the object had not been rendered useless by disposal. For objects where disposal actually does something, both values would be initially true, and would become false afterDispose
. For objects where disposal doesn't need to do any cleanup, the first method could always return false and the second one always true, without having to store a flag anywhere. I don't think there's any way those can be added to .NET now, though.