skip to Main Content

Is there a way to enable compilation errors in Visual Studio 2022 for code that is inside the #else clause of a #if Debug...#else conditional? I have a bit of code like so

#if Debug
    // do some stuff
#else
  // do some other stuff, but this code has compilation errors
#endif

My issue is when compiling the code in Visual Studio, it ignores the text inside the #else clause. Thus, if there are compilation errors they are not flagged as errors and compilation is successful, even if the code in the #else clause has errors.

This is routinely causing me to have compilation errors when building on the build server, because these compilations errors are not seen locally. I could remove the conditional and add them before check in, but that is a pain. There has to be a better way.

Google hasn’t been much help. Any suggestion on how to handle this problem?

2

Answers


  1. There has to be a better way.

    There is, the Conditional attribute:

    [Conditional("DEBUG")]
    void Trace() { /* ... */ }
    

    Calling the Trace function above will be removed from code if its condition isn’t defined, but it will still be parsed by the compiler for correctness.

    Login or Signup to reply.
  2. I would recommend some way to specify configurations explicitly used for debugging. This might be command line parameters, the registry, or just a file that you put somewhere. If you add security sensitive things to this file it might be a good idea to use conditional compilation to ensure all settings have default values unless running in debug. I would at least consider making these settings accessible globally.

    That would turn your conditional compilation into something like

    if(DebugSettings.IsDebug){...}
    else {...}
    

    or

    var credentials = DebugSettings.AzureCredentials ?? Settings.AzureCredentials;
    

    if this for some reason is not possible you could try something like

    #if DEBUG
        if(???){
            // do stuff
            return; // return to ensure other stuff is not run
        }
    #endif
        // do some other stuff
    

    The trick here is to make ??? something that is true, but the compiler cannot prove is true, otherwise you will get unreachable code errors.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search