How To Implement IDisposable Interface

The IDisposable Interface exposes the Dispose method which must be implemented by any class that inherits this Interface. It should be used to release any un-managed resources of an object that have been initialized, like Database connections, handles, streams and files. You should also call GC.SuppressFinalize. This will keep your object from landing on the .NET finalization queue. When you land on this queue, you really do not know when your resources will be released by the Garbage Collection.

Here is a sample class that inherits IDisposable:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Globalization;
using System.Diagnostics;

namespace CallIdisposable
{
   class clsDisposable : IDisposable
   {
       StreamReader reader = null;

       public clsDisposable() { }

       public void ReadFileStream(string _path)
       {
           if (!File.Exists(_path))
               throw new Exception("file not found");
           reader = new StreamReader(_path);
           string _record = string.Empty;
           while (_record != null)
           {
               _record = reader.ReadLine();
               if(_record != null)
                   Console.WriteLine(_record.ToString());
           }
       }
       public void Dispose()
       {
           reader.Dispose();
           //remove from the finalize queue.
           GC.SuppressFinalize(reader);
       }
   }
}

Call the class

string path = @”C:\Users\sam\Documents\SQL\employees.dat”;
clsDisposable cd = new clsDisposable();
cd.ReadFileStream(path);
cd.Dispose();

  • Share/Bookmark

This entry was posted on Thursday, December 3rd, 2009 at 7:51 am and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

 

Leave a Reply