Announcement

Wednesday, October 13, 2010

Dear C# Programmers, please use 'using' and 'IDisposable'

In C++ world, RAII (Resource Acquisition Is Initialization) is a widely accepted idiom. It used by std::auto_ptr<>, CComPtr<>, CWaitCurstor and all smart pointer implementations, streams, etc etc manage the lifetime of resources (e.g. memory, files, cursors, database connections etc). RAII ties the life time of a resource to a life time of a 'local object' (i.e. a object on stack). C++ guarantees that destructors of the objects on stack get call in face of exceptions, multiple returns from functions etc. However, the technique 'as it is' is not directly useful in C# since in C# all objects are created on heap.

Since it is a very useful technique, Microsoft added an interface IDisposable and a keyword 'using' to .Net. It gives all the advantages of RAII.

Recently I saw code similar to following
Stream astream=null;
try
{
    astream = new FileStream(...)
    ....
    // do some processing on stream  
}
catch(...)
{
  
}
finally()
{
    if( astream != null)
    {
       astream.Close()
    }
}
The developer was trying to ensure that stream is closed in case of any exception is thrown (or multiple returns). However, there is much simpler way to do achieve the same result. Rememer 'Stream' objects implement IDisposable interface.  So you can achieve this same effect simply by
using (astream = new FileStream(...))
{
    ....
    // do some processing on stream   
}
It is smaller, simpler and easier to understand. This code clearly indicates, what is the expected life of 'astream'.  With Garbage collector .Net (somewhat ) automates managements of one types of resource i.e. memory. However, there is no good way to manage other types of resources (like files) in face of exceptions where a 'guaranteed release' at certain point is required. Since GC doesn't really guarantee at what object will get garbage collected, tieing resource release to object lifetime doesn't work well. IDispose and 'using' keyword address this concern.
Even though this functionality is available in C#/.Net for a long time, many C# developers don't seem to use it. Probably because they are not really aware of the benefits. Hence my dear C# programmers, please learn about IDisposable/'using' keyword and use it regularly. It will make your life easier. In fact, I will recommend that as much possible make your own classes IDisposable

1 comment:

Deo said...

looks like you are still in good touch of coding, which I miss these days
-Deodatta