Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create versions of a class library in order to support multiple versions of the .NET Framework?

I'm trying to author a family of class libraries which are used between multiple applications within the organization. Some of those applications target .NET 3.5 and some target 4.0.

We want to provide two versions of the assemblies, one targeting 3.5 and one targeting 4.0, so that the host applications can select whichever assembly is most appropriate for them.

There are some subtle differences between the 3.5 and 4.0 versions:

  • Some classes have been removed due to being superseded by .NET 4.0 versions.
  • Some classes have been added to assist working with classes introduced by .NET 4.0.
  • Some classes have been modified in the 4.0 version to take advantage of some of the enhanced threading support in 4.0.

Is there any solution that will allow me to re-use the overlapping portions of the code-base and prevent simply forking the source tree?

My objective is to produce multiple versions of the assemblies targeting their specified frameworks which can be rolled into a NuGet package and exposed on our internal feed.

like image 677
Paul Turner Avatar asked Dec 26 '22 23:12

Paul Turner


1 Answers

This sounds like a job for conditional compiler directives.

Pepper your code with:

#If NET35
...
#End If

and

#If NET40
...
#End If

From here, you have to add the NET35 and NET40 compilation constants to your project, and I would suggest first creating custom configurations in the configuration manager, such as DebugNET35, DebugNET40, ReleaseNET35, and ReleaseNET40. Once those configurations are created, you can switch to each configuration and go to the Advanced Compile Options for your project, where you can set the custom constants NET35 or NET40, depending on the current configuration.

You can also set the target framework in this dialog box, but it will set your framework version globally. To set a custom target framework for each configuration, follow Pierre's Steps.

After that, pick a configuration and compile! I've used this technique to share the same code base for "Demo" and "Full" versions of an application.

Hopefully, future versions of Visual Studio will include framework version defines automatically: https://connect.microsoft.com/VisualStudio/feedback/details/113323/include-framework-version-defines-automatically

Edit: There's a new article in the .NET Framework Blog that discusses writing portable code libraries in Visual Studio 2010 and 2012: http://blogs.msdn.com/b/dotnet/archive/2012/07/06/targeting-multiple-platforms-with-portable-code-overview.aspx, and this looks like a much cleaner solution.

like image 66
MCattle Avatar answered May 01 '23 10:05

MCattle