Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement interface depending on framework version

I'm writing a library, and I want a class to implement and make use of IReadOnlyList<T> if possible. However, that interface is only available starting at framework version 4.5, and I don't want to be tied to that version just because of this one interface.

Is there a way I can automatically compile two versions of the library, one for 4.5 (that will implement the interface, and possibly have some other features as well), and another for 3.5?

As an example, I'm looking for something like an MSBuild configuration that says "compile this library in two [or more] versions" and then specify different options for each one, like defined symbols, framework, references, etc.

If this is possible, it could actually solve a number of other similar problems I've been having.

like image 840
GregRos Avatar asked Dec 26 '22 05:12

GregRos


2 Answers

You could use a compiler directive, e.g.

#if NET45
//specific code for .NET 4.5
#endif

Then create two projects, one for each version, using the Project Linker to maintain a single codebase. In the .NET 4.5 project you can specify the NET45 variable on build. This way the code in the #if block will only be used in one of the versions.

like image 83
Bas Avatar answered Jan 05 '23 01:01

Bas


You can make two versions of the project file, targeting different framework versions. In this case I would place all the project files in the existing project directory.

In each project, you would define a symbol indicating the framework version (as needed), for example DOTNET45. You can do this under Properties - Build - Conditional Compilation Symbols

Then you can use the #if directive:

class MyClass<T> : IList<T>
#if DOTNET45
    , IReadOnlyList<T>
#endif
{
    // Your usual code

    #if DOTNET45

    // IReadOnlyList implementation

    #endif
}

This could get messy however. So alternatively, you could use partial classes:

partial class MyClass<T>
{
}

#if DOTNET45

partial class MyClass<T> : IReadOnlyList<int>
{
    // IReadOnlyList implementation
}

#endif

Obviously partial classes can also be divided over files, so potentially you could do without #if altogether, by only including this partial class file in the .NET 4.5 version of the project.

like image 35
Thorarin Avatar answered Jan 04 '23 23:01

Thorarin