1

I want to write my own Equals-method for two ILists. I've started with null checks and list entry counts. I thought I checked all possibilities,nevertheless after the null-checks I got the compiler-warning "Dereference of a possibly null reference." for the length check. x and y can't be null after the null-checks or did I miss something? With x is not null && y is not null && x.Count != y.Count) there is no warning, but shouldn't the compiler know this implicitly with the checks earlier? I know I could use the !-Operator (null forgiving operator), but does this solve the root of the problem?

Here's the code:

    public bool Equals(IList<int>? x, IList<int>? y)
    {
        if (x is null & y is null)
        {
            return true;
        }
        else if (x is null & y is not null)
        {
            return false;
        }
        else if (x is not null & y is null)
        {
            return false;
        }
        else if (x.Count != y.Count) //warning: y and x could be null
        {
            return false;
        }
        else
        {
            .....
        }
    }

Thanks in advance for enlighting me.

Spoomer
  • 38
  • 5
  • Regardless of your checks, the compiler just goes by the type; if the type is nullable, it will give those warnings. What exactly is the point of having a nullable `IList?`? – CodingYoshi Jan 16 '22 at 16:30
  • I don't think you are quiet right, because in the solution from dmitry, there is no warning. Good Question. I don't have an alternative, when I want to implement IEqualityComparer. Sorry I didn't copied this in. – Spoomer Jan 17 '22 at 21:11

1 Answers1

0

Despite you use the & operator instead of the &&, it's seems that the compiler generates false-positive in your case.
You could simplify your logic as follows:

public static bool Equals(IList<int>? x, IList<int>? y)
{
    if (x is null)
    {
        return y is null;
    }
    if (y is null)
    {
        return false;
    }
    if (x.Count != y.Count) // No warning
    {
        return false;
    }
    ...
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • Thank you. I don't quiet understand, why the compiler generates false-positive, but you are right. PS: There was the warning also with the && Operator. – Spoomer Jan 16 '22 at 14:42