Framework Dependent Conditional Compilation

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:


and / or


After each of these enter:

<DefineConstants Condition=" '$(TargetFrameworkVersion.Replace(&quot;v&quot;,&quot;&quot;))' &gt;= '4.0' ">NET_40_OR_GREATER</DefineConstants>

You can then implement conditional compilation as follows:

    var y = new Tuple();
    var y = new MyTupleReplacementClass();

or whatever it is you need to do.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s