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