17

Using the DEBUG configuration, I can switch behaviour on and off using this type of syntax:

#if DEBUG
    Console.WriteLine("Debug");
#else
    Console.WriteLine("Not Debug");
#endif

However, if I set up a different configuration, say: TEST then this doesn't work:

#if TEST
    Console.WriteLine("Test");
#else
    Console.WriteLine("Not Test");
#endif

Is there a way to check these?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
  • read this http://stackoverflow.com/questions/3167617/determine-if-code-is-running-as-part-of-a-unit-test – NinjaDeveloper Jul 15 '16 at 12:42
  • Add "TEST" to Project Properties -> Build -> Conditional Compilation Symbols, and it works –  Jul 15 '16 at 12:43
  • 1
    For the record - you don't actually check the configuration in your program. #if is a pre-compiler directive, that means it is being executed in the process of the compilation. So the #if .. #else structure isn't a part of your program. – enkryptor Jul 16 '16 at 17:35
  • Note, you may need to restart Visual Studio for this to display properly in the editor. I did on VS 2017. However, the compilation works as you would expect even without a restart. Seems to be an issue with the rendering of directives. – David Oct 10 '18 at 19:05

2 Answers2

11

Yes you can use different configurations. DEBUG symbol is generated automatically if you choose Debug configuration in your configuration manager. You can check it. Go to Your project -> Properties -> Build -> Define DEBUG constant

If you need to use additional constant just enter your own in Conditional compilation symbols.

Steps for your case:

  1. Go to Your project -> Properties -> Build
  2. Switch configuration to Test
  3. Enter TEST to Conditional compilation symbols field

Run your code and enjoy :)

eldrex
  • 143
  • 9
10

The DEBUG constant is a special one, and there's a setting for each project in each configuration whether it should be defined. The default is that it's on in Debug and off in Release, but it's completely configurable - open the properties page for a project and look under "Build", and there's a checkbox there saying "Define DEBUG constant."

Thus, defining a new build configuration, does not automatically give you any other compile constants for free. But that doesn't mean you can't create them manually.

To create a compile constant, add it to the list of "Conditional Compilation Symbols" - but make sure to do so in the correct build configuration.

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
  • 1
    Just to clarify further: to add your compile constant to the list of "Conditional Compilation Symbols" in the Visual Studio gui, just enter the names of your constants separated by semicolons and they'll be set to true: `NOTDEVMODE; DEFINITELYNOTDEVMODE` – Jason Masters Mar 04 '21 at 17:37