dotnet / csharplang

The official repo for the design of the C# programming language
11.57k stars 1.03k forks source link

[Proposal]: Nullable analysis of LINQ queries #3951

Open jcouv opened 4 years ago

jcouv commented 4 years ago

Nullable analysis of LINQ queries

Summary

Nullable analysis of LINQ queries (LDM expressed interested to handle Where, needs design proposal)

Motivation

Range variables in LINQ queries are currently treated as oblivious to minimize annoyances. Most of the annoyance results from our inability to recognize method calls that filter out null elements, such as .Where(i => i is not null).

using System.Linq;
using System.Collections.Generic;

#nullable enable
public class C 
{
    public void M(IEnumerable<string?> list) 
    {
        _ = from item in list
            select item.ToString(); // should warn

        _ = list
            .Where(i => i is not null)
            .Select(i => i.ToString()); // should not warn
    }
}

Detailed design

TBD

Unresolved questions

Design meetings

Split issue from https://github.com/dotnet/csharplang/issues/3868 https://github.com/dotnet/csharplang/blob/main/meetings/2022/LDM-2022-09-28.md#nullability-improvements https://github.com/dotnet/csharplang/blob/main/meetings/2024/LDM-2024-09-06.md#nullable-analysis-of-linq-queries

gafter commented 3 years ago

Would these warnings only be suppressed for the "standard" Linq implementations that have the expected semantics, or for all query expressions (even those that do not have the expected semantics)?

JTeeuwissen commented 2 years ago

Note that OfType currently can be used to filter out nulls whilst getting the correct return type. But perhaps there are more cases where this would not apply.