FP/FN 1764: Impure methods are not guarenteed to return the same value twice

Rule 1764 states that equal expressions on both sides of the && operator should be changed, as this is likely a bug. That sounds all reasonable and fair, but than check this code:

namespace System.Collections.Generic;

internal static class Extensions
{
    [Pure]
    public static bool HasSingle<T>(this IEnumerable<T> items)
    {
        var iterator = items.GetEnumerator();
        return iterator.MoveNext() && !iterator.MoveNext(); // Okay?!
    }

    [Pure]
    public static bool HasMultiple<T>(this IEnumerable<T> items)
    {
        var iterator = items.GetEnumerator();
        return iterator.MoveNext() && iterator.MoveNext(); // Not Okay?!
    }
}

This rule allows iterator.MoveNext() && !iterator.MoveNext() but flags on iterator.MoveNext() && iterator.MoveNext(). If the rule (in this case wrongly) assumes that calling .MoveNext() will always give the same result, both should be wrong. Otherwise, bot should be okay.

It would be nice if the rule can take the [Pure] attribute into account to decide if expressions containing methods can be considered identical. Unfortunately, the .NET team has decided not to use the attribute itself to decorate pure functions.

I’m convinced that both expressions should be evaluated both the same way, and I assume this scenario is so uncommon that you decide to go for not okay, but that’s a call you should make for yourselves.

Reported by NuGet Gallery | SonarAnalyzer.CSharp 10.22.0.136894

Hello again @Corniel ,

I see 2 things here.

1 - The rule should not raise for `iterator.MoveNext() && iterator.MoveNext()` as the method is usually impure so in reality those two conditions are not identical. This is an FP indeed.

2- The condition `a && !a` is always false. (this is responsibility of Rule S2583)

I don’t understand how `PureAttribute` is playing a role for a generic approach? Could you please elaborate?

Thanks

If pure methods were (almost) always decorated as such, you could ignore this rule if methods were not decorated as such, but that would lead to to a lot of false negatives, that was my point.

Indeed, I agree for the false negatives.
I would not add this exception.