There's a very useful class called IndentedTextWriter in the System.CodeDom.Compiler namespace that automatically adds whitespace before each line depending on its Indent property.  This works great when you have code with several nested (or recursive) subroutines and you want them to print nested output but you don't want to keep track of how "nested" they are by yourself.  Unfortunately, there's a bug in the framework's implementation that prevents the first line from being indented.  To illustrate, take this program:

static void Main(string[] args)
IndentedTextWriter writer = new IndentedTextWriter(Console.Out);
writer.Indent = 1;
writer.WriteLine("First line");
writer.WriteLine("Second line");
writer.WriteLine("Third line");

You'll notice that the first line isn't indented:

The bug is easy to fix with a little reflection.  Before the first Write or WriteLine simply call typeof(System.CodeDom.Compiler.IndentedTextWriter).GetField("tabsPending", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(writer, true);

I've attached a simple wrapper class that applies the fix automatically and moves the IndentedTextWriter class to the more common System.IO namespace at the same time.  Enjoy!


Comments (1)
  1. Menno says:

    Wow, 9 years later and this is still not fixed. Thanks man, you saved me hours of work.

Comments are closed.

Skip to main content