What is the importance of finalize method in .NET?You might
already know that developers need not perform memory management in .NET
as that is taken care of by the garbage collector automatically. However
garbage collector releases and cleans up memory used by managed resources.
But there are circumstances where in you might use unmanaged resources such as file, database connectivity in your code. Such unmanaged resources are not cleaned up by garbage collector. For cleaning up unmanaged resources, there are two solutions: Using
Finalize method This article
focuses upon the first option and the Finalize method will be demonstrated
using C#. The finalize method is available as a member of System.Object
and its signature is shown below: This is a do-nothing method which really adds value when you explicitly override it in the derived class and perform the necessary activities. You can use finalize method to perform one of the following activities: Free
any third party objects used in your code How do you use/override Finalize method in your code? You are not permitted to call Finalize method directly, though you are generally allowed to call base class method from derived class. Consider the following example: namespace
Application1 { In this example, you explicitly call Finalize method using an instance of sampleClass. This is not permissible and you will end up in the following error during execution: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. You are also not allowed to override the Finalize method. Consider the following example: namespace
Application1 { Execution of above code will end up in the following warning message and error message: Warning :
Introducing a 'Finalize' method can interfere with destructor invocation.
Did you intend to declare a destructor? The errors in themselves give you the solution. You cannot call or override Finalize method in your code; instead you have to use destructor to implement Finalize method. Consider a simple program using StreamReader to access a file. The file handler instance of StreamReader becomes an unmanaged resource and hence you have to close it inside your destructor. How do you do it? Here is the solution: namespace
Application1 { Sample.txt file used in the above code contains the text as shown in the screenshot below: Output of the above example will be: Contents
of sampleFile: Even though using destructors is the solution for implementing Finalize method, how did this happen? Actually the destructor you have coded above will be internally converted into: protected
override void Finalize() {
|