简体   繁体   中英

C# langversion at 7.3 but IDE still allows me to add ?? (null-coalescing operator)

I'm using C# 7.3 on Visual Studio 2019 (Version 16.9.2). The IDE allows me to use the null-coalescing operator and it builds without errors.

I don't have a Directory.Build.props file anywhere and I have the following in my csproj:

<PropertyGroup>
    <LangVersion>7.3</LangVersion>
</PropertyGroup>

I expect this limits me to C# version 7.3, and when I confirm with #error version I see this:

Error CS8304 Compiler version: '3.9.0-6.21160.10 (59eedc33)'. Language version: 7.3.

So I know I really am using C# 7.3.

Why can I still use the ?? null-coalescing operator? Any troubleshooting tips?

Here's an excerpt from the official documentation on the operator :

In C# 7.3 and earlier, the type of the left-hand operand of the?? operator must be either a reference type or a nullable value type. Beginning with C# 8.0, that requirement is replaced with the following: the type of the left-hand operand of the?? and??= operators cannot be a non-nullable value type.

In other words, the null coalescing operator does exist and is allowed in C# 7.3 and prior. Using C# 7.3 only limits you from putting a regular value type (struct or primitive) on the left side. Even here, the distinction between the two is subtle.

Basically, the only restriction in either situation is you must have a left-hand operand that is actually allowed to be null .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM