CSharpCodeGenerator Tips and Tricks

Here are a couple of tips and tricks with code generation for C#:

  • You do not have to send a parameter of type CodeGeneratorOptions to the GenerateCodeFromCompileUnit method. null is sufficient.
  • The CodeGeneratorOptions class contains some interesting things, like the BracingStyle property. Setting this to “C”, instead of the default “Block” (funny how there are no constants for these) will format your code more nicely, conforming more to the format done by Visual Studio.NET’s reformatting (Ctrl+A, Ctrl+K+F).
  • I looked into this after Roy asked me about it: Verbatim string literals (strings prepended by a @) will only be generated if the string’s size is between 256 and 1500 characters long. And it always will. This means that if your string is less that 256 characters long or 1500 or more characters long it will always be generated as a regular string literal. Otherwise, it will always be generated as a verbatim string literal.
    I found this using Reflector, but didn’t understand why. Looking through Rotor for an answer, I found it here on line 317, where it says that:

    // If the string is short, use C style quoting (e.g “\r\n”)
    // Also do it if it is too long to fit in one line

    Funny how this shows nowhere in the documents, is typed into the code and there are no constants or properties to change this…

By the way, for those of you who care only for my CodeDOM posts, I added a new category to my weblog, CodeDOM Adventures.
I won’t be offended if you choose to only subscribe to those. No, really. ;)


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s