I’m making a few test cases and noticed I needed to check to see if MyObject was Equal to another MyObject.
I created my Equals methods like so:
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == typeof(MyObject) && Equals((MyObject) obj);
}
public bool Equals(MyObject other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.listItems, listItems);
}
public override int GetHashCode()
{
return (TimeBlocks != null ? TimeBlocks.GetHashCode() : 0);
}
There’s a List called listItems that is not evaluating to true. The listItem is of another object type that does have an override on the Equals method.
How does the List decide if one list is equal to another?
Should I be checking each item against the other instead?
Well, first off, the overload for Equals that takes a MyObject is treating
listItemsas static. If that’s the case so be it, but my guess is that was a typo and thatMyObject.listItemsshould beother.listItemsinstead.Anyway. If listItems is a
List<OtherObject>, the List class itself doesn’t override Equals, so it only uses the Object overload which compares hash codes, and for Object those hash codes are based on the object reference. So, two List variables will only be equal if they reference the same List.To make it work the way you want, you’ll need to loop through the list and compare items. Exactly how you do that depends on whether order matters:
The first method, given two equal lists, will be linear; the second will be N^2 complexity and while you could probably improve on that it would be complicated.