How to implement finalize dispose pattern in c#
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
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.
How to implement finalize dispose pattern in
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()
Here is full code
public class Garbage : IDisposable
public String name = String.Empty;
public SqlConnection con = null;
name = "This is managable resource";
con = new SqlConnection();
protected virtual void Dispose(bool disposing)
//Free managed resource here
name = null;
//Free unmanaged resource here
con = null;
Console.WriteLine("Object has disposed");
public void Dispose()
static void Main(string args)
Garbage g = new Garbage();
Console.WriteLine("String created" + g.name);
g.Dispose(); //Dispose the g object
How it works?
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.
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.