4

I am using CodeDom to generate C# code, and part of that involves to spitting out String variable contents. Sometimes, these strings can get to be quite long.

Is there a way to prevent the CodeDom code generator from splitting those large strings into smaller chunks? What the generator does is that it splits the long strings into a few smaller ones, and inserts a concatenation operator in between. While the code compiles fine, I don't like how it messes up the readability of my code.

Satyajit
  • 523
  • 4
  • 17
  • 1
    Why are you wanting/needing it to produce readable code? – Damien_The_Unbeliever Feb 25 '11 at 13:28
  • 1
    There are various reasons for that. The most common use case is when you want to get rid of CodeDom code generators (e.g. refactor them using another technology, like T4 templates), and you need them to produce output source code which is easier to be compared with. Many devs overkill code generation using CodeDom, when they actually should just use a simple, more maintainable, and more human-readable technology to achieve the same results. – sɐunıɔןɐqɐp Feb 03 '19 at 13:41

2 Answers2

4

Hmm.. I don't think so. Poking with .NET Reflector into the source code of Microsoft.CSharp.CSharpCodeGenerator (System's internal), we find this:

private void GeneratePrimitiveExpressionBase(CodePrimitiveExpression e)
{
...
    else if (e.Value is string)
    {
        this.Output.Write(this.QuoteSnippetString((string) e.Value));
    }
...
}

and ... this:

private string QuoteSnippetString(string value)
{
    if (((value.Length >= 0x100) && (value.Length <= 0x5dc)) && (value.IndexOf('\0') == -1))
    {
        return this.QuoteSnippetStringVerbatimStyle(value);
    }
    return this.QuoteSnippetStringCStyle(value);
}

And if you dig further, both functions are not configurable.

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • That's too bad. Thank you for pointing me to the appropriate private method inside CSharpCodeGenerator, I was able to atleast determine that the split happens every 80 chars. – Satyajit Feb 25 '11 at 13:15
  • Actually, the first split occurs after 81 chars, and subsequent splits occur after 80 chars. Although it is a workaround, I do prefer [Satyajit's solution](https://stackoverflow.com/a/5147334/823321): simply use CodeSnippetExpression with double quotes, and replace special chars in the string when necessary (e.g. \n, \r, \t, double quotes, etc). – sɐunıɔןɐqɐp Feb 03 '19 at 12:18
2

I think I have found a way around this: In short, instead of using a CodePrimitiveExpression to output my string, I was able to use a CodeSnippetExpression by explicitly quoting my string argument to it.

CodeExpression x = new CodeSnippetExpression("\"" + myLongString + "\"");

Works for the few cases where I've had to use it, but of course I haven't tested all scenarios.

Satyajit
  • 523
  • 4
  • 17