Dot Net For All

Finalize And Dispose Differences in C#

Hello Friends, in my previous article I have discussed about the use of Finalize and Dispose. In this article I will go though the Finalize and Dispose difference in .NET Framework.

Finalize And Dispose Difference

I will start with the Dispose. Below are the important points we should keep in mind while using Dispose.

Dispose in C#:

  1. Dispose is manual implementation of the IDisposeable pattern. Any class which uses unmanaged resource should implement IDisposeable interface.
  2. The dispose method can be called manually when we are done with the use of the implementing class.
  3. There is no memory pressure added when we use the Dispose method of the class.
  4. The Dispose method belongs to the IDispose interface. Any class which is using unmanaged resource need to implement this interface in C# and VB.NET.
  5. All the classes having a Finalize method should implement a Dispose.
  6. If there is a Finalize method in the same class, you should suppress the invocation of Finalize using GC.SupressFinalize().
  7. The derived class should not implement the IDisposable if the base class already implements it. That is the reason we have to write the method as protected virtual as I did in my previous article.

Finalize in C#:

  1. The call to the Finalize is totally non deterministic. The programmer cannot decide when to call the Finalize method.
  2. Finalize method is the part of the object base class.
  3. Finalize method should not be empty. If there are no unmanaged resource in the class there is no need to have a Finalize method. Implementation of Finalize method could result in memory overhead.
  4. Finalize method name is same as class name preceded by tilde(~) operator.
  5. .NET framework creates a different thread to keep track of the classes implementing Finalize methods.
  6. Finalizers should always be protected, not public or private so that the method cannot be called from the application’s code directly and at the same time, it can make a call to the base.Finalize method

These were some of the difference of the Finalize and Dispose in .NET framework which can help you to understand the two. And this is one of the very common interview question for C# developer and software engineer.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview