I was browsing a coworkers c# code today and found the following:
using (MemoryStream data1 = new MemoryStream())
using (MemoryStream data2 = new MemoryStream())
{
// Lots of code..........
}
I had always seen the using
statement followed by a pair of curly braces that defined the scope of the object life. My coworker who wrote the code said that the curly braces for the data1
using
statement weren't needed and the code did the same thing as if they were present and nested the data2
using
statement. So, what happens when the curly braces are ommitted?
using
statements, as above, are far more readable than nestedusing
statements. Particularly in cases where you're chaining together 3-4 Streams/StreamReaders to perform a single set of operations.using
blocks tends to be rather cut and dried. I don't think I've ever had an occasion to insert some logic in between two stackedusing
statements, and I rarely have to modify them in any way once they're written.using (var data1 ...) { using (var data2 ...) { using (var data3 ...) { MethodCall(data1, data2, data3); } } }