-1

One of the great advantages is supposed to be value based/structural equality, but how do I get that to work with collection properties?

Concrete simple example:

public record Something(string Id);
public record Sample(List<Something> something);

With the above records I would expect the following test to pass:

    [Fact]
    public void Test()
    {
        var x = new Sample(new List<Something>() {
            new Something("x1")
        });
        var y = new Sample(new List<Something>() {
            new Something("x1")
        });
        Assert.Equal(x, y);
    }

I understand that it is because of List being a reference type, but does it exist a collection that implements value based comparison? Basically I would like to do a "deep" value based comparison.

Tomas Jansson
  • 22,767
  • 13
  • 83
  • 137
  • I guess I could convert it to json and compare the json, but that doesn't seems like an optimal solution to the problem. – Tomas Jansson Dec 10 '21 at 12:01
  • [related](https://stackoverflow.com/q/63813872/2501279). – Guru Stron Dec 10 '21 at 12:05
  • 1
    Thanks @GuruStron, so it seems the answer is no... it doesn't exist. That's a shame. I've been in F# land for too long and there we get spoiled of it out of the box. – Tomas Jansson Dec 10 '21 at 12:23
  • 2
    Does this answer your question? [record types with collection properties & collections with value semantics](https://stackoverflow.com/questions/63813872/record-types-with-collection-properties-collections-with-value-semantics) – Richard Deeming Dec 10 '21 at 12:28

1 Answers1

0

Records don't do this automatically, but you can implement the Equals method yourself:

public record Sample(List<Something> something) : IEquatable<Sample>
{
    public virtual bool Equals(Sample? other) => 
        other != null &&
        Enumerable.SequenceEqual(something, other.something);
}

But note that GetHashCode should be overridden to be consistent with Equals. See also implement GetHashCode() for objects that contain collections

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188