Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - Nullable reference type information not exposed from FirstOrDefault

I wanted to test out the new nullable reference types feature in C# 8.0.

I started a new project targeting .NET Core 3.0, enabled nullable reference types in the .csproj file, and started coding. I created a simple list that takes a string[] and returns the string in that array that equals abc. Now, because I am not certain that abc actually exists in the array, I use FirstOrDefault(), which should default to null if a match is not found.

using System;
using System.Linq;

public string FindArgument(string[] args)
{
    var arg = args.FirstOrDefault(x => x == "abc");
    return arg;
}

My method returns string, which should now be the non-nullable type. Since FirstOrDefault() may return null, I would expect the above method to yield a warning when returning the maybe null arg variable. It does not.

Looking at the the signature for FirstOrDefault() in Visual Studio, it is clear why: The method returns a string, not the nullable equivalent string? I would expect.

Using the method body below does yield the warning I expected:

var arg = args.Contains("abc") ? "abc" : null;
return arg;

Do system libraries (in this example System.Linq) really not expose nullability information when targeting .NET Core 3.0?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like System.Linq is not nullable annotated in the 3.0 release. So Nullable Reference Types does not emit the correct warning.

You can check similar problems in the roslyn repo. This open issue on Github is very similar to your problem. In that issue a contributor explains the current problem:

System.Linq is nullable annotated in master branch of corefx, but not in release/3.0. So there's nothing unexpected in compiler. The compiler should provide some diagnostics showing that you are using nullable-oblivious stuff.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...