Search code examples
c#preprocessorverbatim-string

Verbatim string containing "#" recognized as a preprocessor directive


#if DEBUG
    string s = @"
# text";
#endif

If DEBUG is defined the above code builds without error using Visual Studio 2017.

If DEBUG is not defined, the build fails with this error:

error CS1024: Preprocessor directive expected

The issue has been reported to the C# language design community here.

I can work around the problem by using non-verbatim strings:

#if DEBUG
    string s = "\n" +
"# text";
#endif

In my particular use case I would rather keep my strings verbatim. Is there a different - possibly better - way to work around this problem?


Solution

  • If you can't go through, then go around.

    const string shellScript = @"
    # text";
    #if DEBUG
        string s = shellScript;
    #endif
    

    The compiler will not warn about unused constants, nor (I hope) will any overzealous static analysers. As an added benefit (?) you get to explain what the verbatim string actually represents.