IDisposable interface in .NET

IDisposable interface is to release unmanaged resources. This framework would detect that an object is no longer needed as soon as it occurs and automatically free up the memory. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used, it has only a single member called Dispose. This method is called when the object needs to be freed.

Example

 
using System;
 
using System.Collections;
 
using System.Collections.Generic;
 
using System.Data;
 
using System.Diagnostics;
 
using System.Drawing;
 
using System.IO;
 
using System.Windows.Forms;
 
using System.Drawing.Printing;
  
 
public class dispo
 
{
     public static void Main()
     {
         textfile1 textfile = new textfile1("c:\\demo.txt");
         textfile.insertvalue("Example of IDisposable");
  
         textfile.Dispose();
         textfile = null;
         Console.WriteLine("Press Return to collect the garbage...");
         GC.Collect();
  
         Console.WriteLine("Press Return to quit...");
         Console.ReadLine();
     }
 }
  
 
public class textfile1 : IDisposable
 
{
     private FileStream str;
     private bool id;
     public textfile1(string filename)
     {
         str = new FileStream("test.txt", FileMode.OpenOrCreate);
         Console.WriteLine("Object " + GetHashCode() + " created.");
         Console.WriteLine("Using file: " + filename);
     }
  
     public void insertvalue(string buf)
     {
         if (id == true)
         {
             throw new ObjectDisposedException("I've been disposed!");
         }
  
         StreamWriter wr = new StreamWriter(str);
         wr.WriteLine(System.DateTime.Now);
         wr.WriteLine(buf);
         wr.Close();
     }
  
     public void Dispose()
     {
         if (id == true)
             return;
  
         str.Close();
         str = null;
  
         id = true;
  
         GC.SuppressFinalize(this);
  
         Console.WriteLine("Object " + GetHashCode() + " disposed.");
     }
 }

Output

dispo.gif

Ebook Download
View all
Learn
View all