Reputation: 38
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.
Upvotes: 1
Views: 169
Reputation: 14059
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;
}
...
}
Upvotes: 0