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);
}