Nested Blocks
Eric Gunnerson points out a condensed way of writing nested using statements to alleviate indentation headaches.
using (StreamWriter w1 = File.CreateText("W1"))
using (StreamWriter w2 = File.CreateText("W2"))
{
// code here
}
This was not an explicitly added to the C# as a feature of using; it's a byproduct of the using statement being able to take any embeddable statement, whether it is contained in a block or not.
using (TextReader file = File.OpenText("file"))
str = file.ReadToEnd();
This behavior is also true for the fixed statement, so you can write fixed blocks in the same manner or even interweave the both using and fixed as in the following example.
using (TextWriter file1 = File.CreateText("file1"))
fixed (char *p = str)
using (TextWriter file2 = File.CreateText("file2"))
{
// code here
}
The C# editor will recognized nested using and fixed statements and not indent them as it would do for any other embedded statements. For instance, while the lock keyword has nearly the same syntax and can take embedded statements, the C# formatter in VS will still cause each inner lock statement to be indented.
lock (a)
lock (b)
{
// code here
}
Great tip! I like this a lot better than indented using statements!
...more discussion
http://blog.magenic.com/seans/archive/2004/08/06/261.aspx
Posted by: Sean Schade | August 06, 2004 at 06:29 AM
Or even better, you can do the following using just one using statement:
using (StreamWriter w1 = File.CreateText("W1"), w2 = File.CreateText("W2"))
{
// code here
}
As long as the types are the same...
Posted by: David M. Kean | August 07, 2004 at 01:09 AM