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?
Asked
Active
Viewed 5,463 times
3 Answers
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
-
1Just 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
-
7This 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
-
1Does not help those of us who'd like to use Mono-specific features... – BlueRaja - Danny Pflughoeft Jun 26 '13 at 16:43