Search code examples
c#debuggingconditional-compilationvisual-studio-macros

How do I alter code at compile time based on a flag in C#


I want to set up a debug flag such that would replace "Console".Writeline with "Log".WriteLine. I don't want to write

if (debug)
    Log.writeline("log");
else 
    Console.Writeline("log"); every time I want to log info.

Something like INFO.Writelline("log"); where INFO could be replaced by "Log" or "Console" depending a global variable set.
Would have used conditional Macro but C# does not support that. Please let me know if I am missing something.


Solution

  • Something like this?

    #define MY_DEBUG //Note: this must be the first line in the file
    
    public static class INFO
    {
        public static void WriteLine(string message)
        {
             #if (MY_DEBUG)
                 Log.writeline(message);
             #else
                 Console.Writeline(message);
             #endif
        }
    }
    

    And you would just call

    INFO.WriteLine("log message");