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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With