0

I am attempting to implement Equals overrides for some structs in my code. I have the following "child" struct

public struct ChildStruct
{
    public bool Valid;
    public int Value1;

    public override bool Equals(object obj)
    {
         if (obj == null || GetType() != obj.GetType()) 
         {
             return false;
         }

         ChildStruct other = (ChildStruct) obj;

         return Valid == other.Valid && Surface == other.Value1;
    }
}

And this "parent" struct where one member is an array of ChildStructs

public struct ParentStruct
{
    public int Id;
    public ChildStruct[] children;

    public override bool Equals(object obj)
    {
         if (obj == null || GetType() != obj.GetType()) 
         {
             return false;
         }

         ParentStruct other = (ParentStruct) obj;

         // am I comparing ChildStructs array correctly?
         return Id == other.Id && children == other.children;
    }
}

In my Nunit testing of overriding the Equals methods, directly comparing objects of type ChildStruct pass, but my unit test of the ParentStructs are failing. Am I missing something in the Equals override in the ParentStruct to account for the array? Is the child Equals method not enumerated to all elements in the children array?

Nunit code:

[Test]
public void ChildEqual()
{ 
    var child1 = new ChildStruct{Valid = true, Value1 = 1};
    var child2 = new ChildStruct{Valid = true, Value1 = 1};

    // passes!
    Assert.AreEqual(child1, child2);
}

[Test]
public void ParentEqual()
{ 
    var child1 = new ChildStruct{Valid = true, Value1 = 1};
    var child2 = new ChildStruct{Valid = true, Value1 = 1};

    var parent1 = new ParentStruct{Id = 1, children = new[] {child1, child2}}
    var parent2 = new ParentStruct{Id = 1, children = new[] {child1, child2}}

    // fails during checking for equality of children array!
    Assert.AreEqual(parent1, parent2);
}
David Owens
  • 645
  • 6
  • 25

1 Answers1

1

You need to determine what makes two arrays of ChildStructs equal, for the purpose of ParentStruct equality, and change the last line of ParentStruct's equals method accordingly. For example, if they're only supposed to be "equal" if they contain equivalent children in the same order, this would work:

return Id == other.Id && children.SequenceEqual(other.children);
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • Ahhh got it. I was making the false assumption that calling `Equals` on an array would delegate behind the scenes to each items own `Equals` method. – David Owens Nov 13 '19 at 18:42