[Mono-list] Making code conditional on "not running on mono"?

Aleksey Demakov avd@openlinksw.com
Sat, 17 May 2003 13:07:29 +0700


Stuart Ballard wrote:
> I have a C# program which uses some classes (specifically 
> System.DirectoryServices) that aren't implemented in Mono. The code in 
> question is not critical to the application and the majority of the 
> functionality would work fine if it wasn't there. I can't remove the 
> code entirely (because in some cases we actually do need the 
> functionality) but I can't compile on Mono with it present, because the 
> classes aren't found.
> 
> Is there any way I can avoid having to have two different copies of the 
> source code, one for Mono without the feature and one for MS.NET with 
> the feature included?
> 
> Thanks,
> Stuart.

If it's ok to have a separate assembly for each platform
you can use conditional compilation as follows:

...
#if M0NO
   Console.WriteLine ("Platform: Mono");
#else
   Console.WriteLine ("Platform: .NET");
#endif
...

And don't forget to compile it with mcs /d:MONO :).

If you want to have not only common source code but also
single assembly for all platforms then use a runtime check.
This one worked fine for me:

...
Type enumType = typeof (PlatformID);
if (Enum.IsDefined (enumType, "Unix"))
{
   if (Environment.OSVersion.Platform == (PlatformID) Enum.Parse 
(enumType, "Unix"))
     Console.WriteLine ("Platform: Mono on Unix");
   else
     Console.WriteLine ("Platform: Mono on Win32");
}
else
   Console.WriteLine ("Platform: .NET");
...

Regards,
Aleksey