dotnet / roslyn-analyzers

MIT License
1.58k stars 464 forks source link

Suggest getting the span of List<T> for iterations #7344

Open Meir017 opened 3 months ago

Meir017 commented 3 months ago

consider the following code:

public void Method(List<int> list)
{
    // should trigger the analyzer
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    list.ForEach(Console.WriteLine);

    // the suggested fix
    foreach (var item in CollectionsMarshal.AsSpan(list))
    {
        Console.WriteLine(item);
    }
}

Iterating over List without getting the span first.

Describe suggestions on how to achieve the rule

my current solution for List<T>.ForEach is using the https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers.md and banning the List<T>.ForEach and having a comment suggesting to use our extension method ForEachSpan which gets the span from the list and then iterates over the list

sharwell commented 2 months ago

💭 I'm not sure the gains for this are worth giving up the _version check.