Is there a compiler directive for C# 8 or detecting if <nullable>enable</nullable>
is set?
I have a source code only Nuget package that could stand to help with the nullable reference types story. I'd like to conditionally set the #nullable enable
directive if this is set, such as:
#ifdef ICANHASNULLABLE
#nullable enable
#endif
and
#ifdef ICANHASNULLABLE
string Foo(string? val)
#else
string Foo(string val)
#endif
I have a mix of stuff built with the .NET Core 2.1 SDK and am working to bring things to .NET Core 3.1, albeit slowly and not just by flipping a switch. The directive only points to the framework versions, not language version.
Assume you have a multi targeting app. In your .csproj
file:
<PropertyGroup>
<TargetFrameworks>netcoreapp2.2;netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
You could add a conditional PropertyGroup
specific to netcoreapp3.1
and have your own constant defined:
<PropertyGroup Condition="'$(TargetFramework)'=='netcoreapp3.1'">
<DefineConstants>ICANHASNULLABLE</DefineConstants>
<Nullable>enable</Nullable>
</PropertyGroup>
You can also define your directive based on <Nullable>
:
<PropertyGroup Condition="'$(Nullable)'=='enable'">
<DefineConstants>ICANHASNULLABLE</DefineConstants>
</PropertyGroup>
In your code, you could use ICANHASNULLABLE
:
#if ICANHASNULLABLE
void Foo(string? val)
#else
void Foo(string val)
#endif
{
}
Default language version for netcoreapp 3.x is C# 8.0 . So any PropertyGroup
specifically defined for netcoreapp3.1
in the above example could be considered as specific to C# 8.0 if LangVersion
is not set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.