Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolate Mono-specific code

Tags:

c#

mono

I'm playing with adding Gtk# GUI to a Windows.Forms application. I need a way to isolate Mono-specific code in Program.cs since I'd like to avoid creation of a separate .sln/.csproj. In C/C++/Objective-C projects, I'd do something similar to #ifdef __APPLE__ or #ifdef _WIN32.

C# appears to have the #if command.

What is the typical way to isolate Mono-specific code, or Visual Studio-specific code?

like image 592
Ivan Vučica Avatar asked Mar 01 '11 20:03

Ivan Vučica


1 Answers

You can define a symbol using #define and check against it, using #if and #else.

You can also pass the symbol to the compiler using the /define compiler option.

See the complete list of C# Preprocessor directives here.

#define MONO // Or pass in "/define MONO" to csc 

#if MONO
 //mono specific code
#else 
 //other code
#endif

According to this SO answer, the mono compiler defines a __MonoCS__ symbol, so the following would work:

#if __MonoCS__
 //mono specific code
#else 
 //other code
#endif

The recommended method that the Mono "Porting to Windows" guide, as detailed in this answer by @Mystic, is:

public static bool IsRunningOnMono ()
{
    return Type.GetType ("Mono.Runtime") != null;
}

This, of course, is a runtime check, versus the compile time checks above so may not work for your specific case.

like image 190
Oded Avatar answered Oct 22 '22 21:10

Oded