Do you ever have the need to compile .NET code in two or more versions of the framework? Probably. And usually it is not a big deal, since each successive release of the framework is almost fully backwards-compatible. But what about forward-compatibility – yeah, sounds like an oxymoron doesn’t it? But sometimes the need for it crops up.
Recently I have been learning to use Unity3d. I would like to use it as the presentation layer of some code I have developed separately. However, my code was developed using the 4.0 .NET framework and Unity3d will only handle DLLs created with 3.5 or earlier.
Simple: recompile in 3.5.
Nope: I use Tuples and other 4.0 features not available in 3.5.
I really don’t want to rip apart all my 4.0 code and replace my Tuples with classes, etc. Especially since it seems that Unity3d will support 4.0 soon (and I’ll just want to rip it apart and put Tuples back in). But what to do in the meantime?
Enter framework dependent conditional compilation, a handy trick that I found here. Open your csproj file and look for the sections that define the DEBUG and TRACE preprocessor constants:
<DefineConstants>DEBUG;TRACE</DefineConstants>
and / or
<DefineConstants>TRACE</DefineConstants>
After each of these enter:
<DefineConstants Condition=" '$(TargetFrameworkVersion.Replace("v",""))' >= '4.0' ">NET_40_OR_GREATER</DefineConstants>
You can then implement conditional compilation as follows:
#if NET_40_OR_GREATER var y = new Tuple(); #else var y = new MyTupleReplacementClass(); #endif
or whatever it is you need to do.