Nested Blocks

8/6/2004 2:16:43 AM

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
    }

Comments

 

Navigation

Categories

About

Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media