Records returning false on enumerable equality

Viewed 1637

Testing out the new C# 9 Records, and wanting clarification on why sequence equality doesn't work on Records?

Say that I have the below code:

public record Person(string FirstName, string LastName);

The following code will return true for equality (nothing surprising here):

var first = new Person("Bruce", "Wayne");
var second = new Person("Bruce", "Wayne");
var result = first == second; // Returns true

However if I create the following record:

public record Basket(string[] Items);

And I do a similar test:

var first = new Basket(new[] { "Banana", "Apple" });
var second = new Basket(new[] { "Banana", "Apple" });
var result = first == second;

The result will return false. This can be solved by defining your own Equals method:

public record Basket(string[] Items)
{
    public virtual bool Equals(Basket other)
    {
        return Items.SequenceEqual(other.Items);
    }

    public override int GetHashCode() => Items.GetHashCode();
}

But am curious as to the decision behind this (if any).

0 Answers
Related