Difference between Finalize and Dispose Methods

Chakravarthi
Posted by in C# category on for Beginner level | Points: 250 | Views : 32505 red flag

In this article we will discuss about the major differences between the Finalize and Dispose Methods in C#

Finalize


1 ) Used to free unmanaged resources like files, database connections, COM etc. held by an object before that object is destroyed.

Sample code:
// Implementing Finalize method
public class MyClass 
{
 //At runtime C# destructor is automatically Converted to Finalize method.
 ~MyClass ()
 {
 //TO DO: clean up unmanaged objects
 }
}

2) Internally, it is called by Garbage Collector and cannot be called by user code.

3) It belongs to Object class.

4) Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.

5) There is performance costs associated with Finalize method.

6) Syntax for this method is protected virtual void Finalize()

7) By default Object.Finalize method does nothing. If there is need then we must be overridden by a derived class or provide destruction.  

Example :

using System;
using System.Diagnostics;

public class Example
{
   Stopwatch sw;

   public Example()
   {
      sw = Stopwatch.StartNew();
      Console.WriteLine("Instantiated object");              // Instantiated object 
   } 

   public void ShowDuration()
   {
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }

   ~Example()
   {
      Console.WriteLine("Finalizing object");                 // Finalizing object
      sw.Stop();
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }
}

public class Demo
{
   public static void Main()
   {
      ExampleClass ex = new ExampleClass();
      ex.ShowDuration();
   }
}

Output would be like this :
  Instantiated object 
  This instance of Example has been in existence for 00:00:00.0010070 
  Finalizing object 
  This instance of Example has been in existence for 00:00:00.0054926

Dispose

1) It is used to free unmanaged resources like files, database connections, COM etc. at any time.

Sample code:
// Implementing Dispose method
public class MyClass : IDisposable
{
      	  private bool disposed = false;
 
	  //Implement IDisposable.
	  public void Dispose()
	   {
	     Dispose(true);
	   }
 
	 protected virtual void Dispose(bool disposing)
 	{
	 if (!disposed)
	  {
	   if (disposing)
	   {
	     //TO DO: clean up managed objects
	   }
 
	  //TO DO: clean up unmanaged objects
 
	   disposed = true;
 	  }
	 }
}
2) Explicitly, it is called by user code and the class implementing dispose method must implement IDisposable interface.

3) It belongs to IDisposable interface.

4) Implement this when you are writing a custom class that will be used by other users.

5) There is no performance costs associated with Dispose method.

6) Syntax for this method is void Dispose()

7) To implementing this method, ensure that all current resources are must be freed.
     For example, if an object A allocates an object B, and object B allocates an object C, then object A's Dispose implementation must call on B's Dispose, and which must in turn call on C's Dispose. 

Example :
using System;
using System.ComponentModel;

public class DisposeExample
{
    public class MyResource: IDisposable  
    {
        
        private IntPtr handle; // Pointer to unmanaged resource. 
private Component component = new Component();
private bool disposed = false; public MyResource(IntPtr handle) // The class constructor
{ this.handle = handle; } // Implement IDisposable. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { component.Dispose(); // Dispose managed resources } CloseHandle(handle); handle = IntPtr.Zero; disposed = true; // Note disposing has been done
} } // to clean up the unmanaged resource [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(IntPtr handle); ~MyResource() { Dispose(false); } } public static void Main() { // Insert code here to create // and use the MyResource object } }

Conclusion


Thanks for Reading , Hope this article will be useful.  

Page copy protected against web site content infringement by Copyscape

About the Author

Chakravarthi
Full Name: Annabattula Ashok Chakravarthi
Member Level: Starter
Member Status: Member
Member Since: 7/4/2013 11:49:03 PM
Country: India
Chakravarthi
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)