roslyn: IsNullOrEmpty isn't treated as a null reference check
The preview 8 compiler is unable to correctly interpret string.IsNullOrEmpty
method call and produces a warning warning CS8602: Dereference of a possibly null reference.
, but it must not. The same thing happens with IsNullOrWhiteSpace
.
string? nullableString = null;
int y = string.IsNullOrEmpty(nullableString) ? 24 : nullableString.Length;
int z = string.IsNullOrWhiteSpace(nullableString) ? 24 : nullableString.Length;
The problem can be worked around by using value?.Length > 0
instead of the method.
Previously was discussed in #37328 and marked as fixed.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 10
- Comments: 22 (16 by maintainers)
If you want to multi-target and take advantage of nullability analysis, you may wish to enable nullable warnings only in the target frameworks which have nullable annotations for the core libraries.
Something like:
I ran into this too. What is the guidance for library authors that multi-target and want to take advantage of nullability?
@YohDeadfall This is happening because you are using a target (.NET Standard 2.0) that does not have any nullable annotations in the framework.
I don’t want to add one just for this.
I’ve added my own wrapping methods: https://github.com/JamesNK/Newtonsoft.Json/pull/2163. It’s not pretty but it works.
As to why this worked previously, for previews there were a few APIs that were special-cased in the compiler. Those special cases have been removed and we now rely on annotations, which are present in netcoreapp3.0 and netstandard2.1, but not net4x or netstandard2.0
Why did this use to work? This only became a problem in preview 8.
I’m creating a package with a
netstandard2.0
target (among others) that I want to use nullable reference types with: Newtonsoft.Json. What is the solution here?I could write my own internal implementations of
string.IsNullOrEmpty
andDebug.Assert
, and add attributes to them, then use them throughout the Newtonsoft.Json source code. That seems like kicking the problem onto end developers.