Nested Using Statements Redux

Many people have been responding to my previous post on the subject, this way or another.
What seems to be a reoccurring complaint is that you can’t put two resource acquisitions of different types in the same line.
So I sat down and found a way to do this.

Let’s take Sean’s code:

using(TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
using(MemoryStream ms = new MemoryStream(inBytes.Length))
using(CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(__desKey, __desIV), CryptoStreamMode.Read))
{
ms.Write(inBytes, 0, inBytes.Length);
ms.Position = 0;
string outString = new StreamReader(cs).ReadToEnd();
cs.Close();
outBytes = ASCIIEncoding.ASCII.GetBytes(outString);
return outBytes;
}


The above code can use only one using statement, using the currently available language features.
However, it would look like this:

TripleDESCryptoServiceProvider des; MemoryStream ms; CryptoStream cs;
using (IDisposable ides = des = new TripleDESCryptoServiceProvider(),
ims = ms = new MemoryStream(inBytes.Length),
ics = cs = new CryptoStream(ms, des.CreateDecryptor(__desKey, __desIV), CryptoStreamMode.Read))
{
ms.Write(inBytes, 0, inBytes.Length);
ms.Position = 0;
string outString = new StreamReader(cs).ReadToEnd();
cs.Close(); // By the way, you don't need this. Dispose for stream closes them.
outBytes = ASCIIEncoding.ASCII.GetBytes(outString);
return outBytes;
}

Well, you got what you wanted, didn’t you?

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