2018-08-19

Multi-targeting framework libraries


Today, I’ve a new demand: How to create a .NET library available for .NET 3.5 and .NET 4.0.

The first solution is to create the library with the framework 3.5 and use it in 4.0… but that’s not the best solution.

The easier solution is to create a Visual Studio solution with references to two projects. Each project sets the correct framework (in project properties) and defines a compilation constant (NET35 or NET40) with MSBuild configuration (see below).

I’ve opened each .csproj to add this MSBuild script (adapted for 3.5 or 4.0):

  <PropertyGroup>
    <TargetFrameworkName>.NET Framework 3.5</TargetFrameworkName>
    <DefineConstants>NET35;$(DefineConstants)</DefineConstants>
    <OutputPath>$(BaseOutputDirectory)bin\$(Configuration)\$(TargetFrameworkName)</OutputPath>
    <IntermediateOutputPath>$(BaseOutputDirectory)obj\$(Configuration)\$(TargetFrameworkName)</IntermediateOutputPath>
    <DocumentationFile>$(OutputPath)\Trasys.Dev.xml</DocumentationFile>
  </PropertyGroup></pre>

Next, we can use a precompilation constants to check which version of framework is used.

  #if NET35
    // Code used only with framework 3.5
  #endif

Leave a Reply

Your email address will not be published. Required fields are marked *