BlackM
BlackM

Reputation: 4065

C# Equality in ObservableCollection

I have a custom object which I have successfully overriden the Equals and HashCode function. Then I have 2 Observable Collections on which I initialise the exact same objects (but with different reference). So I have this code:

if (qObjects.Equals(qObjects2))
{
    Console.WriteLine("Arrays are equal");
}

which I am expecting to return true but returns false. You might say that I did something wrong with Equal and HashCode function. But this is the weird:

for (int i = 0; i < qObjects.Count(); i++)
{
    arraysIsEqual = qObjects[i].Equals(qObjects2[i]);

    if (!arraysIsEqual)
    {
        break;
    }
}

if (arraysIsEqual)
{
    Console.WriteLine("Arrays are equal");
}

The above code snippet returns true. So what I am missing here?

Upvotes: 4

Views: 3413

Answers (1)

slawekwin
slawekwin

Reputation: 6310

When you are comparing collections with Equals, the ObservableCollection objects themselves will be compared. This obviously results in false, because the collection's class does not override Equals (it's inherited from Object so compares references). In order not to have to iterate objects yourself, you can use SequenceEqual method. (Confusingly not the SequenceEquals method).

if (qObjects.SequenceEqual(qObjects2)) {
   Console.WriteLine("Arrays are equal");
  } 

Upvotes: 11

Related Questions