[ # ] Using the using-statement

/* Posted April 21st, 2008 at 10:42am */
/* Filed under C#, Microsoft, Programming */

“Using statement?”, you may ask. “What is so interesting about that? I use it every day importing tons of namespaces!”
Well, i mean the other using statement; that one that results in a nice try..finally in IL, without having to write lots of code.

Well lets say you want to access a file, a database, or whatever resource that needs to be closed after usage:

StreamReader sr = new StreamReader(@”c:\mytextfile.txt”);
sr.ReadToEnd().Count(); // just doing something
sr.Close(); // closing a resource explicitly. gooood!

The problem here is: If the file for example is not encoded correctly, or you’re just doing something inbetween opening and closing your reader that might fail, your resource will not be closed until the GC disposes it. This in some cases might mean, until your application is closed.
Putting a try catch arround it helps:

StreamReader sr = null;
try
{
sr = new StreamReader(@”c:\mytextfile.txt”);
sr.ReadToEnd().Count(); // just doing something
}
finally
{
if (sr != null) // StreamReader.ctr() could fail…
sr.Close();
}

The using statement does exactly the same. The IL-Code also looks pretty similar, but it is way easier to write.

using(StreamReader sr = new StreamReader(@”c:\my.txt”))
{
sr.ReadToEnd().Count(); // just doing something
}

The using-statement takes any object implementing IDisposable. In the end or in case of any error, it will safely dispose the used resource. The Dispose()-Method on Streams or any other Reader/Writer in usually does the same thing as Close() does.
You can even nest them if you have to use multiple resource at once:

using(StreamReader sr1 = new StreamReader(@”c:\my1.txt”))
using (StreamReader sr2 = new StreamReader(@”c:\my2.txt”))
using (StreamWriter sw = new StreamWriter(@”c:\mynew.txt”))
{
sw.WriteLine(sr1.ReadToEnd());
sw.WriteLine(sr2.ReadToEnd());
}

Almost any resource usage in .Net, for example ADO.Net implements the IDisposable on their classes. The connection will be closed and disposed, the transaction will be rolled back if something fails before commit.

using (var conn = new SqlConnection(”…”))
{
using (var st = conn.BeginTransaction())
{
conn.Open();
var sc = conn.CreateCommand();
sc.CommandText = “UPDATE …”;
sc.ExecuteNonQuery();
var sc2 = conn.CreateCommand();
sc2.CommandText = “SELECT …”;
using (var reader = sc2.ExecuteReader())
{
return reader.GetString(0);
}
st.Commit();

}
}

  • Digg
  • del.icio.us
  • Propeller
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Mixx
  • NewsVine
  • Blogsvine
  • Facebook
  • Google
  • TwitThis


Related Posts

One Response to “Using the using-statement”

 Comment from Agravar [April 21, 2008, 11:29 am]

Ooooo that’s neat!

Leave a Reply


*


* (not published, used to display your gravatar)



(* required)

Anything Geeky Goes!

Highlights

Featured Wii

Featured iPhone

Featured PSP/PS3

Featured A/V

Related Links

Archives

Products Highlight


Featured Sites

Categories

Subscribe

  • rss 1.0 feed
  • rss 2.0 feed
  • atom feed
  • atom feed
Email:

Recent Posts

Commentors

Other Links