So a using statement automatically calls the dispose method on the object that is being \"used\", when the using block is exited, right?
But when is this necessary/benef
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.
I asked a very similar question here:
Resources that have to be manually cleaned up in C#?
And i got a nice piece of advice in the form of:
In general, if something has a Dispose method, you should call it when you've finished with it, or, if you can, wrap it up in a using statement.