How to conditionally compile against different .NET framework versions in F#

I recently needed to supply two variations of an algorithm in an F# source file – one for .NET 3.5 consumers and another for .NET 4.0 consumers (the later framework version allows parallel execution using the FSharp.Collections.ParallelSeq). One way is to tell msbuild to reference the library, conditional on the version of the .NET framework – and also, define a constant which can be used within the source code to choose the algorithm.

In msbuild, define a constant according to the framework

<PropertyGroup Condition=" '$Framework' == 'NET35' ">
  <DefineConstants>NET35</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$Framework' == 'NET40' ">
  <DefineConstants>NET40</DefineConstants>
</PropertyGroup>

In msbuild, reference library if .NET 4.0

<ItemGroup Condition=" '$Framework' == 'NET40' ">
  <Reference Include="FSharp.Collections.ParallelSeq"/>
</ItemGroup>

Specify conditional compilation directives in the source code

let doMapping = ... // some transformation
#if NET35
    items |> Seq.map doMapping
#else
    items |> FSharp.Collections.ParallelSeq.PSeq.map doMapping

Leave a comment

Filed under F#, Programming

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s