Reader Level:

Using Dispose method in C#

By Ashish Singhal on Feb 17, 2006
This artice will explain about Finalize and Dispose method implementation in C#.

This peice of code will show you some memory management in classes.

When we give application to client, we dont know how will he use that whether he will call dispose or not?

It may be missing at client side so our application should be smart enough to free used resources, here is code
which will give Idea to implement finalizer and dispose in same class to take care of resource cleaning.

using System;

namespace disposeConsole


          class ResourceManagement : IDisposable


                   public ResourceManagement()


                   private bool IsDisposed = false;

                   public void Free()


                             if (IsDisposed)

                                      throw new System.ObjectDisposedException("Object Name");


                   //Call Dispose to free resources explicitly

                   public void Dispose()


                             //Pass true in dispose method to clean managed resources too and say GC to skip finalize
                             in next line.


                             //If dispose is called already then say GC to skip finalize on this instance.





                             //Pass false as param because no need to free managed resources when you call finalize it
                             will be done

                             //by GC itself as its work of finalize to manage managed resources.




                   //Implement dispose to free resources

                   protected virtual void Dispose(bool disposedStatus)


                             if (!IsDisposed)


                                      IsDisposed = true;

                                      // Released unmanaged Resources

                                      if (disposedStatus)


                                                // Released managed Resources






Ashish Singhal
Ashish Singhal

Ashish has been working as a software engineer since 2002. He has written articles for C# Corner . He specializes in the implementation of client/server, database, graphics and/or Internet-based systems using Visual Stud... Read more



Spire.Doc - Free .NET Word API
Use Spire.Doc to create, read, write, print, and convert word documents to OpenXML, RTF, TXT, XPS, EPUB, EMF, HTML, Image and PDF.

Trending up

Infragistics jQuery Controls