If I write a class in C# that implements IDisposable, why isn't is sufficient for me to simply implement
public void Dispose(){ ... }
to handle freeing any unmanaged resources?
Is
protected virtual void Dispose(bool disposing){ ... }
always necessary, sometimes necessary, or something else altogether?
A protected override void Dispose(bool) method that overrides the base class method and performs the actual cleanup of the derived class. This method must also call the base. Dispose(bool) ( MyBase. Dispose(bool) in Visual Basic) method passing it the disposing status ( bool disposing parameter) as an argument.
In the context of C#, dispose is an object method invoked to execute code required for memory cleanup and release and reset unmanaged resources, such as file handles and database connections.
Dispose is for releasing "unmanaged" resources (for example, sockets, file handles, Bitmap handles, etc), and if it's being called outside a finalizer (that's what the disposing flag signifies, BTW), for disposing other IDisposable objects it holds that are no longer useful.
It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary. At runtime C#, C++ destructors are automatically converted to Finalize method.
The full pattern including a finalizer, introduction of a new virtual method and "sealing" of the original dispose method is very general purpose, covering all bases.
Unless you have direct handles on unmanaged resources (which should be almost never) you don't need a finalizer.
If you seal your class (and my views on sealing classes wherever possible are probably well known by now - design for inheritance or prohibit it) there's no point in introducing a virtual method.
I can't remember the last time I implemented IDisposable
in a "complicated" way vs doing it in the most obvious way, e.g.
public void Dispose() { somethingElse.Dispose(); }
One thing to note is that if you're going for really robust code, you should make sure that you don't try to do anything after you've been disposed, and throw ObjectDisposedException
where appropriate. That's good advice for class libraries which will be used by developers all over the world, but it's a lot of work for very little gain if this is just going to be a class used within your own workspace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With