[Mono-dev] Cross Platform on Linux/Windows with Mono.Posix reference on Linux

Edward Ned Harvey (mono) edward.harvey.mono at clevertrove.com
Tue Mar 29 03:27:10 UTC 2016

> From: mono-devel-list-bounces at lists.ximian.com [mailto:mono-devel-list-
> bounces at lists.ximian.com] On Behalf Of Greg Young
> <Reference Include="Mono.Posix" Condition=" '$(OS)' != 'Windows_NT' " />

That doesn't do the trick all by itself, because then your code won't compile on windows, in all the places where something references Mono.Posix. If you want to use this as a solution, you'll need to define a compiler symbol in the project, and maintain different project files (or different build configurations) when building on windows or mono, and then #if to remove references to Mono.Posix, when built in windows. While this technique works, it would result in binaries that are not cross-platform compatible (maybe you don't care). And you have to maintain the separate project files, which is annoying.

The other way is to build a factory, and do a run-time check to load the appropriate assembly. For example, you can put the abstract StuffDoer class in a common assembly, which is available to all your platform agnostic code. Then write a StuffDoerWin derivative class in a windows-only assembly, and a StuffDoerMono class in a mono-only assembly. Choose which one to instantiate using a run-time check, like:

// This is defined in a common assembly
public static abstract class StuffDoer {
	public static StuffDoer CreateInstance() {
		if (Type.GetType("Mono.Runtime") == null) {
			// running on windows
			// Use Activator.CreateInstance to return an object of type StuffDoerWin, from my Windows assembly
			return newStuffDoer;
		} else {
			// running on mono
			// Use Activator.CreateInstance to return an object of type StuffDoerMono, from my Mono assembly
			return newStuffDoer;		}
	public abstract void DoStuff();  // Must be overridden in derivative class

// This is defined in a windows-only assembly
public static class StuffDoerWin : StuffDoer {

// This is defined in a mono-only assembly
public static class StuffDoerMono : StuffDoer {
	// Here, I can use Mono.Posix stuff

More information about the Mono-devel-list mailing list