Using the using statement in C#
I am sure we all know the use of the using statement in C# so I won't go into very much detail about it as that is not the point of this blog entry;
So now that we are all on the same page regarding the use of the statement I would like to address a usability issue regarding this particular gem ...
Consider this example;
using (ObjectX x = new ObjectX)
{
using (ObjectY y = new ObjectY)
{
using (ObjectZ z = new ObjectZ)
{
//TODO: some implementation should go here
}
}
}
I have often needed to nest using statements like this which after a couple of nestings makes your code rather unreadable.
I discovered (purely by accident and was then backed up by a blog entry on Eric Gunnerson's C# Compendium site) that you could do the following instead;
using (ObjectX x = new ObjectX())
using (ObjectY y = new ObjectY())
using (ObjectZ z = new ObjectZ())
{
//TODO: some implementation should go here
}
Which to me is far more readable than the initial code snippet!
What do you guys think?
Does this make the code easier, or (heaven forbid) more difficult to read?