13

I need to dual-compile a class library for Mono on the Mac and .NET on the PC. There are some minor changes I want to make, but I was hoping to split the code using a compiler directive. Any suggestions?

Gabe
  • 84,912
  • 12
  • 139
  • 238
whitehawk
  • 2,429
  • 29
  • 33

3 Answers3

45

While a runtime check is probably preferable, with the Mono compiler, the pre-defined __MonoCS__ constant is useful, e.g.:

#if __MonoCS__
// Code for Mono C# compiler.
#else
// Code for Microsoft C# compiler.
#endif
Stewart
  • 4,223
  • 6
  • 31
  • 39
  • 1
    Just make sure no developer adds __ MonoCS __ to your Visual Studio project build properties and then wonders why the compiled code doesn't work as expected! :-/ – Stewart Sep 10 '12 at 13:08
  • 7
    This is the correct answer and should be marked as such. – BSalita Mar 07 '13 at 11:42
  • I agree with @BSalita this is the correct answer (and it works). In my particular case, I needed to add an interface to a namespace. The Mono version doesn't have it yet. – Nelson Rodriguez Apr 12 '17 at 14:52
  • This works exactly opposite for me. I add this `#if __MonoCS__ using System.Deployment.Application; #endif` - and that compiles. Whereas leaving it out fails. The exact opposite of what should logically happen, since I'm compiling in Mono on a Mac. – PandaWood Aug 05 '18 at 14:11
19

Preferred way is to use runtime detection, as this allows for the same assemblies to be used on either platform:

using System;

class Program {
    static void Main ()
    {
        Type t = Type.GetType ("Mono.Runtime");
        if (t != null)
             Console.WriteLine ("You are running with the Mono VM");
        else
             Console.WriteLine ("You are running something else");
    }
}
skolima
  • 31,963
  • 27
  • 115
  • 151
14

Well you could certainly use

#if MONO

and then compile with

gmcs -define:MONO ...

(Or put it in your Mono build configuration, of course. It really depends on how you're building your library.)

... what are you looking for beyond that?

Gabe
  • 84,912
  • 12
  • 139
  • 238
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194