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
• Using dispose 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:
protected virtual void Finalize() { }

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
• Close any file handlers that are opened in your code
• Free memory used by unmanaged resources
• Close the database connection that is already opened in your code
• Close the network port that is left open 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 {
class sampleClass {
public static void Main() {
sampleClass obj = new sampleClass();
obj.Finalize();
}
}
}

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 {
class sampleClass {
protected override void Finalize(){ }
}
}

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?”
Error: “Do not override object.Finalize. Instead, provide 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 {
class sampleClass {
System.IO.StreamReader sampleReader;
public static void Main() {
sampleClass obj = new sampleClass();
obj.sampleReader = new System.IO.StreamReader("sample.txt");
string eachLine;
Console.WriteLine("Contents of sampleFile:");
while ((eachLine = obj.sampleReader.ReadLine()) != null) {
Console.WriteLine(eachLine);
}
Console.ReadLine();
}
~sampleClass() {
if (sampleReader != null) {
sampleReader.Close();
}
}
}
}

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:
This is a sample text file.
It is used to demonstrate usage of finalize through destructors.
Enjoy reading it from your C# program.

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() {
try {
if (sampleReader != null) {
sampleReader.Close();
}

}
finally {
base.Finalize();
}
}

_______________________________________________________________________

Add to My Yahoo!


FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

Visit .NET Programming Tutorial Homepage

______________________________________________________

Recommended Resource

| How do you prevent a class from overriding in .NET? | How are classes related to objects in .NET Application | How are Delegates different from Events in .NET? | How are system exceptions different from application exceptions in .NET? | How are Value Types different from Reference Types in .NET? | How can a finalize method be suppressed in .NET? | How can you call Stored Procedure in ADO.NET? | How can you force Dispose method to be called automatically in .NET? | How do you call a Base Class Constructor from Derived Class Constructor in .NET? | How do you connect your VB.NET application to SQL Server? | How do you implement Cloning in .NET? | How do you implement Façade Design Pattern in .NET? | How do you implement MVC Pattern in ASP.NET? | How do you install .NET Assembly in GAC? | How is shadowing different from overriding in .NET? | How to prevent a particular .NET DLL from being decompiled? | Illustrate Delay Signing Process of an Assembly in .NET? | What are Reference Types in .NET? | What are the advantages of C#? | What are the advantages of VB.NET? | What are the differences between Namespace and Assembly in .NET? | What are the similar features between class and structure in .NET? | What are Value Types in .NET? | What do you mean by mixed mode authentication in .NET? | What do you mean by Satellite Assembly in .NET? | What do you mean by shadowing in .NET? | What is CTS in .NET? | What is ILDASM in .NET? | What is Managed Code in .NET? | What is Manifest in .NET? | What is MSIL in .NET Framework? | What is the importance of finalize method in .NET? | What is the need for Visitor Pattern in C#? | What is the purpose of bindingRedirect tag in web.config file of .NET? | What is the purpose of CodeDom in .NET? | What is the purpose of dispose method in .NET? | What is the purpose of Ngen.exe in .NET? | What is the purpose of Strong Name in COM Components of .NET? | What is the purpose of virtual keyword in .NET? | What Object Oriented Principles can be incorporated in .NET Application? |


| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2017 - All Rights Reserved.