Is it possible to conditionally compile to .NET Framework version?

There is one big caveat to be aware of when defining custom compilation symbols in your .csproj (or .vbproj, theoretically): they overwrite all previously-defined compilation symbols. For example, consider MSBuild snippet:

  <PropertyGroup Condition="'$(TargetFrameworkVersion)' == 'v4.0'">
    <DefineConstants>$(DefineConstants);DOTNET_40</DefineConstants>
  </PropertyGroup>
  <PropertyGroup>
    <DefineConstants>ITS_CLOBBERING_TIME</DefineConstants>
  </PropertyGroup>

The second DefineConstants element will, as its value suggests, clobber the first value of DefineConstants. To avoid this, you'll want to rewrite the second DefineConstants element to look like this:

    <DefineConstants>$(DefineConstants);ITS_CLOBBERING_TIME</DefineConstants>

Also, you'll want to place this inside of a PropertyGroup defined after all other PropertyGroups, as Visual Studio 2010 currently adds in custom compilation symbols in such a way that it will clobber any other custom compilation symbols you define if they are placed before Visual Studio plops down its definition. I've filed this issue with Microsoft. You can track its progress at Microsoft Connect.


There are no builtin precompiler constants that you can use. But, it is easy enough create your own build configurations in VS with each configuration having its own set of defined constants and of course a target framework version. A lot of people do this to conditionally compile based 32 or 64 bit differences.