When are C# "using" statements most useful?

The 'using' statement is most useful when working with unmanaged objects, like database connections.

In this way, the connection is closed and disposed no matter what happens in the code block.

For more discussion, see this article on CodeProject: http://www.codeproject.com/KB/cs/tinguusingstatement.aspx


Without using (or manually calling Dispose()), the object will eventually be disposed of, just not at a deterministic time. That is, it can happen straight away, in two days' time, or (in some cases) never.

For things like, say, network connections, you want the connection to close when you're done with it, not "whenever", otherwise it'll idle around hogging up a socket.

Further, for things like mutex locks, you do not want those to be released "whenever", or else deadlock is likely to result.


This:

public void DoSomething()
{
    using (Font font1 = new Font("Arial", 10.0f))
    {
        // Draw some text here
    }
}

maps directly to this:

public void DoSomething()
{
    {
        Font font1;
        try
        {
            font1 = new Font("Arial", 10.0f);
            // Draw some text here
        }
        finally
        {
            IDisposable disp = font1 as IDisposable;
            if (disp != null) disp.Dispose();
        }
    }
}

Note the finally block: the object is disposed even if an exception occurs. Also note the extra anonymous scope block: it means that not only is the object disposed, but it goes out of scope as well.

The other important thing here is disposal is guaranteed to happen right away. It's deterministic. Without a using statement or similar construct, the object would still go out of scope at the end of the method and could then be collected eventually. The resource then would ideally be destroyed so it can be reclaimed by the system. But "eventually" might not happen for a while, and "would ideally" and "will" are very different things.

Therefore, "eventually" isn't always good enough. Resources like database connections, sockets, semaphores/mutexes, and (in this case) GDI resources are often severely limited and need to be cleaned up right away. A using statement will make sure this happens.