Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# IList Equals: Why is there a nullable compiler warning if the nullable typ could not be null?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading