2

Consider this generic identity function:

T Id<T>(T x) => x;

If I use it in a lambda mapping the elements in an array of string? values, it works as expected (i.e. it preserves the information, that the values are nullable).

var xs = new[] { (string?)"foo" };

var ys = xs.Select(x => Id(x)); // inferred type of `ys` is IEnumerable<string?>
string y = ys.Single();         // warning CS8600: Converting [...] possible null value to non-nullable type.

However, if I use it as a method group that information will be discarded.

var xs = new[] { (string?)"foo" };

var ys = xs.Select(Id); // inferred type of `ys` is IEnumerable<string>
string y = ys.Single(); // no warning CS8600

What's going on here? Is this a compiler bug or a known limitation of nullable reference types?

As a workaround I could declare Id like below to get the expected warning in the second example:

T? Id<T>(T? x) => x;

But this seems overly expressive to me.

I'm using C# 10.0.

Working example: https://dotnetfiddle.net/SEHIb6

Good Night Nerd Pride
  • 8,245
  • 4
  • 49
  • 65
  • 1
    I feel this is very similar to [this fixed bug](https://github.com/dotnet/roslyn/issues/40597). Seems like they haven't fixed _everything_. Note that what has happened is that the compiler is happily passing `Id` to a parameter that takes a `Func`. – Sweeper Dec 28 '21 at 16:54
  • Nice find, @Sweeper! Looking through the issues there I found lots of nullability related issues. [This one](https://github.com/dotnet/roslyn/issues/44174) seems to be the exact same problem I'm having. – Good Night Nerd Pride Dec 28 '21 at 18:54

0 Answers0