Search code examples
c#conditional-statementsdebug-symbols

C# Conditional equivalent of !DEBUG


What is the C# System.Diagnostics.Conditional equivalent of #if (!DEBUG)?

I want to encrypt a section of the app.config file of a console application if it has not been compiled in DEBUG mode. This is achieved like so:

public static void Main(string[] args)
{
    #if (!DEBUG)
    ConfigEncryption.EncryptAppSettings();
    #endif
    //...
}

but somehow, I prefer decorating the encrypt method with a conditional attribute:

[Conditional("!DEBUG")]
internal static void EncryptAppSettings()
{
    //...
}

however this makes the compiler sad: The argument to the 'System.Diagnostics.ConditionalAttribute' attribute must be a valid identifier...

What is the correct syntax for negating the Conditional argument?

EDIT: Thanks to @Gusdor, I used this (I preferred to keep the Program.cs file free of if/else debug logic):

#if !DEBUG
#define ENCRYPT_CONFIG
#endif

[Conditional("ENCRYPT_CONFIG")]
internal static void EncryptAppSettings()
{
    //...
}

Solution

  • Using the attribute will be a bit of a hack but it can be done.

    #if DEBUG
    //you have nothing to do here but c# requires it
    #else
    #define NOT_DEBUG //define a symbol specifying a non debug environment
    #endif
    
    [Conditional("NOT_DEBUG")]
    internal static void EncryptAppSettings()
    {
        //...
    }