15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using Database Connections ❘ 823<br />

Within the finally block, you can release any resources you have used. The only trouble with this method<br />

is that you have to ensure that you close the connection — it is all too easy to forget to add the finally<br />

clause, so something less prone to vagaries in coding style might be worthwhile.<br />

In addition, you might find that you open a number of resources (say two database connections <strong>and</strong> a file)<br />

within a given method, so the cascade of try...catch...finally blocks can sometimes become less easy<br />

to read. There is, however, another way to guarantee resource cleanup — the using statement.<br />

option Two: The using Block statement<br />

During development of <strong>C#</strong>, the debate on how .<strong>NET</strong> uses nondeterministic destruction became very heated.<br />

In C++, as soon as an object went out of scope, its destructor would be automatically called. This was great<br />

news for designers of resource-based classes because the destructor was the ideal place to close the resource<br />

if the user had forgotten to do so. A C++ destructor is called whenever an object goes out of scope — so, for<br />

instance, if an exception were raised <strong>and</strong> not caught, all destructors would be called.<br />

With <strong>C#</strong> <strong>and</strong> the other managed languages, there is no concept of automatic, deterministic destruction.<br />

Instead, there is the garbage collector, which disposes of resources at some point in the future. What makes<br />

this nondeterministic is that you have little say over when this process actually happens. Forgetting to close<br />

a database connection could cause all sorts of problems for a .<strong>NET</strong> executable. Luckily, help is at h<strong>and</strong>.<br />

The following code demonstrates how to use the using clause to ensure that objects that implement the<br />

IDisposable interface (see Chapter 13, “Memory Management <strong>and</strong> Pointers”) are cleared up immediately<br />

after the block exits:<br />

string source = "server=(local);" +<br />

"integrated security=SSPI;" +<br />

"database=Northwind";<br />

using ( SqlConnection conn = new SqlConnection ( source ) )<br />

{<br />

// Open the connection<br />

conn.Open ( );<br />

}<br />

// Do something useful<br />

In this instance, the using clause ensures that the database connection is closed, regardless of how the block<br />

is exited.<br />

Looking at the IL code for the Dispose() method of the connection classes, you can see that all of them<br />

check the current state of the connection object <strong>and</strong>, if it is open, will call the Close() method. A great tool<br />

for browsing .<strong>NET</strong> assemblies is Reflector (available at www.red-gate.com/products/reflector/). This<br />

tool permits you to view the IL code for any .<strong>NET</strong> method <strong>and</strong> will also reverse-engineer the IL into <strong>C#</strong><br />

source code, so you can easily see what a given method is doing.<br />

When programming, you should use at least one of these methods, <strong>and</strong> probably both. Wherever you<br />

acquire resources, it is good practice to use the using statement; even though we all mean to write the<br />

Close() statement, sometimes we forget, <strong>and</strong> in the face of exceptions the using clause does the right<br />

thing. There is no substitute for good exception h<strong>and</strong>ling either, so in most instances, it is best to use both<br />

methods together, as in the following example:<br />

try<br />

{<br />

using (SqlConnection conn = new SqlConnection ( source ))<br />

{<br />

// Open the connection<br />

conn.Open ( );<br />

// Do something useful<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!