20
votes

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?

1

1 Answers

14
votes

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.