Using “Using”

0073145363892_600

Among the the most undervalued C# instructions, one could actually save the lives of most developers — or at least eliminate this question often raised Friday night after going live: « Did I close that damn object that I opened? »

Not « using »

The question arises when we open objects of various sizes (database connections, files, etc.) that have a critical impact on the computer’s resources (the memory mainly). In the example that follows, we’ll open a log file to recover its contents: On paper, everything is perfect. Objects are closed, going live poses no problem, my boss will congratulate me, I’ll have a good weekend and all that. But if we look more closely, not quite. Imagine that a problem occurs for one reason or another in the finally block. Exceptions that haven’t been retrieved will prevent the release of objects. So much for the weekend.

Using « using »

If I tell you that you can open objects without worrying about closing them, that’s the whole point of using using statements. Let’s take another look at the previous example: The objects are initialized in a using block. They are only visible and usable in the context in which they are declared. Outside of this context, the objects are automatically released, even when an exception occurs in one of the instruction blocks. To be used in this way, the objects must implement the IDisposable interface which uses the Dispose method when it is deemed necessary.

Using « using » but …

It is possible to declare objects outside the using block, but be sure to keep in mind that these are only available in their respective contexts. Finally, the declared objects are read-only, so it is impossible to reassign them. I can enjoy the weekend. More than an instruction, using is a pal!

KIM DOTNET

For more information:

using Statement (C# Reference)
IDisposable, interface