How to implement finalize dispose pattern in c#
Implement finalize
dispose pattern in C#
In this article
we are going to discuss finalize dispose pattern in C# class. When we want to
clear resource after uses of any object, we can implement this pattern. In
finalize dispose pattern we have to implement one interface called IDisposable
in class where we want to implement. At first, we will understand concept of IDisposable
interface and after that we will implement finalize dispose pattern in one sample
class.
IDisposable interface.
This interface is
placed within System namespace. And it contain only one method called
Dispose() and we have to implement same in class where we will implement
finalize dispose pattern. Signature of
Dispose method is like below.
void Dispose()
How to implement finalize dispose pattern in
class
In below example
we will implement Dispose() function in class called Garbage. If you already
know how to implement Interface in class, by seeing example you will understand.
If not please go through below few lines.
Here we have
implemented Garbage class like class Garbage:IDisposable. and we have implemented
Dispose function like this
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
Here is full code
and implantation.
using System;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
namespace Test1
{
public class Garbage : IDisposable
{
public String name = String.Empty;
public SqlConnection con = null;
public Garbage()
{
name = "This is managable resource";
con = new SqlConnection();
}
~Garbage()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
//Free managed resource here
name = null;
}
//Free unmanaged resource here
con = null;
Console.WriteLine("Object has disposed");
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
class Program
{
static void Main(string[] args)
{
Garbage g = new Garbage();
Console.WriteLine("String created" + g.name);
g.Dispose(); //Dispose the g object
Console.ReadLine();
}
}
}
How it works?
Here,
within class we have created one managed resource (string object) and one
unmanaged resource (connection object) within class. When the object will create
for that class both will initialize and after that when we will call
g.Dispose() method ,the object will get clear from memory.

Conclusion:-
It is always good practice to clean up garbage object manually . Then the chance to run garbage collector will reduce. But it is recommend not to implement finalize dispose pattern in each and every class. Only implement finalize dispose pattern when you are dealing with lot of unmanaged objects in your class.