Dispose Method in C#

Kailash Chandra Behera | Sunday, August 07, 2016

Introduction

This article describes about Dispose method and demonstrates how to use it to clean memory in c#.

Getting Started

Dispose Methos is used to clean up unmanaged resources(For example, Windows API created objects, File, Database connection objects, COM objects, etc) explictly held by objects and goes outside of scope of .Net Framework.

It belongs IDisposable Interface that comes under System namespace, hence to implement Dispose Methos in class that class must have an implementation of this interface. Unlike finalize method, this method needs to call explicitly by the class object.

In the below example the disposeexample has implemented IDisposable Interface for clean unmanaged resourece from memorry

 using System;  
 using System.Collections.Generic;  
 using System.IO;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace Disposableexample  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       disposeexample ip = new disposeexample();  
       Console.WriteLine("File content");  
       Console.WriteLine(ip.ReadFile());  
       Console.ReadLine();  
     }  
   }  
   public class disposeexample : IDisposable  
   {  
     // Flag: Has Dispose already been called?  
     bool disposed = false;  
     private FileStream filestream;  
     private StreamReader streamreader;  
     public string ReadFile()  
     {  
       Console.WriteLine("start reading file");  
       try  
       {  
         filestream = new FileStream(Path.Combine(Environment.CurrentDirectory, "TextFile1.txt"), FileMode.Open, FileAccess.Read);  
         streamreader = new StreamReader(filestream);  
         Console.WriteLine("reading file completed");  
         return streamreader.ReadToEnd();  
       }  
       catch (Exception ex)  
       {  
         return string.Empty;  
       }  
       finally  
       {  
         streamreader.Close();  
         filestream.Close();  
         this.Dispose();  
       }  
     }  
     protected virtual void Dispose(bool disposing)  
     {  
       Console.WriteLine("Calleing dispose method");  
       if (disposed)  
         return;  
       if (disposing)  
       {  
         filestream.Dispose();  
         streamreader.Dispose();  
       }  
       Console.WriteLine("object disposed");  
       disposed = true;  
     }  
     public void Dispose()  
     {  
       this.Dispose(true);  
     }  
   }  
 }  

Summary

In the above of this article we discussed about Dispose method and with code example, Hope this article may helpful to you.

Thanks