Using “using”

I presented my own code for review in the last PMR group meeting and thankfully came off very lightly. However Nick Day who is currently doing a lot of Clojure work picked me up on something. I had many lines of code similar to:

XPathDocument xPathDocument = new XPathDocument(new StringReader(source));

and he was worried that I was not closing my string reader after use. After a bit of looking around I see that the code should be refactored into:

XPathDocument xPathDocument = null;
using (StringReader sr = new StringReader(source)) {
  xPathDocument = new XPathDocument(sr);
}


This ensures that the StringReader can be disposed of as soon as it has been used to create the XPathDocument. I am not at all surprised that Nick would spot this as it reminds me of the first Clojure macro that I finally got – though that was for a HTTP request.

Of course I could always have done the more conventional (and Java like):

StringReader sr = new StringReader(source);
XPathDocument xPathDocument = new XPathDocument(sr);
sr.Close();
sr.Dispose();

but I find the first way far more elegant and clear and it ensures that the resources are cleaned up no matter what – even if the creation of the XPathDocument throws exceptions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: