Reputation: 678
Is there any predefined constant to distinguish language versions, such as:
#if C#6
//code
#else
//code
#endif
Upvotes: 5
Views: 350
Reputation: 106
Depending on your environment you can rely on the platform version or not. If the projects do not use custom explicit language versions, you can try to use the target framework directives.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version#defaults
.NET Framework
NETFRAMEWORK, NET48, NET472, NET471, NET47, NET462, NET461, NET46, NET452, NET451, NET45, NET40, NET35, NET20
.NET Standard
NETSTANDARD, NETSTANDARD2_1, NETSTANDARD2_0, NETSTANDARD1_6, NETSTANDARD1_5, NETSTANDARD1_4, NETSTANDARD1_3, NETSTANDARD1_2, NETSTANDARD1_1, NETSTANDARD1_0
.NET 5+ and .NET Core
NET, NET6_0, NET6_0_ANDROID, NET6_0_IOS, NET6_0_MACOS, NET6_0_MACCATALYST, NET6_0_TVOS, NET6_0_WINDOWS, NET5_0, NETCOREAPP, NETCOREAPP3_1, NETCOREAPP3_0, NETCOREAPP2_2, NETCOREAPP2_1, NETCOREAPP2_0, NETCOREAPP1_1, NETCOREAPP1_0
https://stackoverflow.com/questions/38476796/how-to-set-net-core-in-if-statement-for-compilation
So you can use if-else directives with these keywords
#if NET5_0
// GG C# 9
#endif
There are also other directive keywords with the higher or lower keyword
#if NET5_0_OR_GREATER // up-level version
#else // down-level version
#endif
This approach is unreliable if you actually need only language version specific features. I recommend to set the latest language version in your csproj.
Upvotes: 1
Reputation: 29538
You shouldn't have to do this.
Typically, you would do something like this to support different versions of .NET framework. Not different versions of the C# compiler. Newer compiler can target older versions of the framework. In short, use the latest C# compiler features. The compiler is free, so there isn't any real roadblock to updating a project to use the latest features.
Upvotes: 2