the following code is from MSDN: Idisposable pattern
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (_resource != null)
_resource.Dispose();
Console.WriteLine("Object disposed.");
}
// Indicate that the instance has been disposed.
_resource = null;
_disposed = true;
}
}
why the following statement:
_resource = null;
_disposed = true;
are not enclosed by if (disposing) statement block?
for me i would probably write like this:
if (disposing) {
if (_resource != null) {
_resource.Dispose();
_resource = null;
_disposed = true;
}
Console.WriteLine("Object disposed.");
}
anything wrong with my version?
The pattern outlined by the MSDN is the only correct way to implement IDisposable because it takes finalization into account. You need to look closely at the IDisposable implementation:
This calls your dispose method, indicating it’s a real dispose and supresses further finalization.
It’s not safe to call out to any other object during finalization, so that’s why you want to set:
to prevent any further mishappenings.
Here’s a good info on finalization and IDisposable on MSDN.