Eric Roller
Eric Roller

Reputation: 437

Resharper claims expression is always false using LINQ Aggregate with seed

In the following code Resharper claims that the expression currMax == null is always false.

public Read Read1
{
    get
    {
        return Reads.Where(read => !read.IsIndex)
                    .Aggregate((Read)null, (currMax, read) => currMax == null || read.Length > currMax.Length ? read : currMax);
    }
}

When the first iteration of the lambda expression in the call to Aggregate executes I would expect currMax == null to be true since (Read)null is the seed. Resharper knows that the upstream Where requires non-null Read objects in the resulting IEnumerable because I am accessing the IsIndex property of the Read class. Does resharper just not take into account the seed parameter to Aggregate?

Edit: I've filed a bug report here https://youtrack.jetbrains.com/issue/RSRP-443055

Upvotes: 4

Views: 337

Answers (2)

ulrichb
ulrichb

Reputation: 20054

This is indeed a bug in ReSharper's nullability analysis. Could you report it to YouTrack?

In the meantime you can suppress this warning with // ReSharper disable once ConditionIsAlwaysTrueOrFalse.

Upvotes: 1

Matthew
Matthew

Reputation: 25773

Looks like ReSharper is wrong, judging from the disassembly of Aggregate in ILSpy.

public static TAccumulate Aggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source, 
    TAccumulate seed, 
    Func<TAccumulate, TSource, TAccumulate> func)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (func == null)
    {
        throw Error.ArgumentNull("func");
    }
    TAccumulate tAccumulate = seed;
    foreach (TSource current in source)
    {
        tAccumulate = func(tAccumulate, current);
    }
    return tAccumulate;
}

Clearly removing the null check will result in a null reference exception.

Upvotes: 1

Related Questions