Sunday, June 23, 2013

.NET Developer Interview Question: What is IDisposable?

Garbage collector as a part of CLR has the responsibility of managing memory allocation to native .NET objects which are called managed objects. C#, VB.NET and other .NET languages which are garbage collected languages does not provide a way for developers to finalize a managed object in their application directly. However not all resources you use in your program is a managed one. Examples of unmanaged objects are window handles, open files, streams and database connections. While CLR's garbage collector automatically releases the memory allocated to managed objects (when they are not needed any longer), it will not be possible to know when garbage collection will occur with unmanaged objects and developers need to take the matter into their own hands. 

When calling a class that implements the IDisposable interface, use the try/finally pattern to make sure that unmanaged resources are disposed, even if an exception interrupts your application. you can use the using statement (Using in Visual Basic) instead of the try/finally pattern.

IDisposable interface is defined as follows:
public interface IDisposable
{
   void Dispose();
}

When writing a class for IDisposable interface, make the dispose method of the class public so that other classes can call the methods:
public class MyClass : IDisposable
{
   public void Dispose()
   {
     //Handle your finalization process here ...
   }
}

1 comment:

  1. Nice blog. Thanks for sharing such great information.Inwizards Inc is a Dot Net Development company offers quality Asp Dot Net development services best in web industries. Intrested click here - Hire .Net Developers India

    ReplyDelete