'Assert anonymous object equivalence

I'm sure i'm missing the obvious...

Say we have:

[Fact]
public void SomeTest()
{
    var a = new { SomeProp = "hello", AnotherProp = 9 };
    var b = new { SomeProp = "hello" };
    var c = new { AnotherProp = 9 };
    var d = new { SomeProp = "hello", AnotherProp = 9 };
}

What is the correct assertion to check that all of the properties match (e.g. a and d would return true, but all other combinations would return false?

At the moment, i'm doing equivalency checks, but have to do it in both directions? e.g.

    a.Should().BeEquivalentTo(d);
    d.Should().BeEquivalentTo(a);

Forgive me if this is clearly defined in the docs... I can't find it :/



Solution 1:[1]

From the microsoft docs:

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

I am not sure about the specifics of .BeEquivalentTo but if it relies on the == operator, this does not guarantee equality for anonymous types.

If the anonymous objects have exactly the same structure (including order) and the same values you can use:

`Assert.True(a.equals(d))

Otherwise you must assert each property manually

Assert.IsEqual(a.name, d.name); 
Assert.IsEqual(a.AnotherProp, d.AnotherProp)

EDIT: You cannot use hash codes to guarantee equality of two dispret objects. See the following from the MS docs:

Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes

Solution 2:[2]

This is by design, which should be self-explanatory from the name.

E.g. if you say "A should be equivalent to B", you are not saying that A is the same as B, nor are you saying that B is equivalent to A.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dennis Doomen