Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should Dispose() be non-virtual?

I'm new to C#, so apologies if this is an obvious question.

In the MSDN Dispose example, the Dispose method they define is non-virtual. Why is that? It seems odd to me - I'd expect that a child class of an IDisposable that had its own non-managed resources would just override Dispose and call base.Dispose() at the bottom of their own method.

Thanks!

like image 500
Sbodd Avatar asked Sep 01 '10 15:09

Sbodd


People also ask

Why do we have the Dispose () method?

The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.

Why we need to implement Dispose method while we have option to implement destructor?

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.

Why is Dispose needed in C#?

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.

Why we use Dispose method in MVC?

The Dispose(Boolean) method overload is the preferred method to override. If you derive a class from Controller and the derived class uses unmanaged memory, managed operating-system resources (such as files), or COM objects, you should implement Dispose to clean up these resources.


1 Answers

Typical usage is that Dispose() is overloaded, with a public, non-virtual Dispose() method, and a virtual, protected Dispose(bool). The public Dispose() method calls Dispose(true), and subclasses can use this protected virtual method to free up their own resorces, and call base.Dispose(true) for parent classes.

If the class owning the public Dispose() method also implements a finalizer, then the finalizer calls Dispose(false), indicating that the protected Dispose(bool) method was called during garbage collection.

If there is a finalizer, then the public Dispose() method is also responsible for calling GC.SuppressFinalize() to make sure that the finalizer is no longer active, and will never be called. This allows the garbage collector to treat the class normally. Classes with active finalizers generally get collected only as a last resort, after gen0, gen1, and gen2 cleanup.

like image 175
Cylon Cat Avatar answered Oct 14 '22 12:10

Cylon Cat