Click here to Skip to main content
15,894,017 members
Articles / Programming Languages / C#

Finalize in .NET

Rate me:
Please Sign up or sign in to vote.
3.00/5 (2 votes)
5 Jun 2012CPOL1 min read 14.4K   4   3
Implementing the Finalize method to release unmanaged resources.

We implement the Finalize method to release unmanaged resources. First let’s see what are managed and unmanaged resources. Managed ones are those, which we write in .Net languages. But when we write code in any non .NET language like VB 6 or any windows API, we call it as unmanaged. And there are very high chances that we use any win API or any COM component in our application. So, as managed resources are not managed by CLR, we need to handle them at our own. So, once we are done with unmanaged resources, we need to clean them. The cleanup and releasing of unmanaged is done in Finalize(). If your class is not using any unmanaged resources, then you can forget about Finalize(). But problem is, we can’t directly call Finalize(), we do not have control of it. Then who is going to call this. Basically GC calls this. And one more thing to remember is, there is no Finalize keyword that we will write and implement it. We can define Finalize by defining the Destructor. Destructor is use to clean up unmanaged resourced. When u will put ~ sign in front of class name, it will be treated as destructor. So, when code is compiled, the destructor is going to convert that into Finalize and further garbage collector will add it to the Finalize queue. Let’s take this sample code:

C#
class A    {
   public A()
   { Console.WriteLine("I am in A"); }
   ~A()
   { Console.WriteLine("Destructor of A"); }
 }

 class B : A    {
   public B()
   { Console.WriteLine("I am in B"); }
   ~B()
   { Console.WriteLine("Destructor of B"); }
 }

 class C : B   {
   public C()
   { Console.WriteLine("I am in C"); }
   ~C()
   { Console.WriteLine("Destructor of C"); }
 }

Now using Reflector, we will see, if Destructor, really converted to Finalize:

And wow, it’s really done. Here we can see that there is nothing like destructor. Basically destructor is overriding the Finalize method.

Hope it helps!!!

This article was originally posted at http://shwetamannjain.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 1 Pin
nobodyxxxxx6-Jun-12 3:47
nobodyxxxxx6-Jun-12 3:47 
GeneralRe: My vote of 1 Pin
Shweta Lodha6-Jun-12 22:42
Shweta Lodha6-Jun-12 22:42 
NewsImage is not getting displayed Pin
Shweta Lodha5-Jun-12 20:47
Shweta Lodha5-Jun-12 20:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.