Search code examples
c#asp.net.netcross-platform.net-standard-2.0

Visual Studio conditional compilation for OS


I know that there is a way to conditionally compile for target frameworks, e.g., #if net461 ....#elif ....

But is there a way to conditionally compile for a specific OS? Like target _os_MAC or target_os_win.

If there is, where are the documentation or tutorials on how to implement it?

Part 2: Also, is there a way to create a custom tag, so that I do not have to change every tag whenever there is a change to the new target OS or framework, e.g., from net461 to net471?


Solution

  • This answer assumes you're asking about custom preprocessor symbols (that is how I have interpreted it - do correct me if I am wrong.

    You could use a custom build configuration:

    Start by going into the build Configuration Manager...

    Configuration Manager

    Next, create a new build configuration. You can copy the configuration from an existing one:

    Create new configuration

    Then, right click on your Project and go to Properties. Under the build tab, define a conditional compilation symbol:

    Conditional compilation symbol

    Do the same for Windows.

    Then you can write conditional steps like the below:

    class Program
    {
        static void Main(string[] args)
        {
            #if MACOS
                Console.WriteLine("OS X");
            #elif WINDOWS
                Console.WriteLine("Windows");
            #endif
    
            Console.Read();
        }
    

    Depending on your chosen build configuration ... you'll either get:

    OS X:

    OS X

    Windows:

    Windows