user230910
user230910

Reputation: 2372

C# Tuple Equality vs Contains in list

I recently encountered some surprising behaviour of a Tuple in a List. It seems that Contains in a list does a different comparison than what I was expecting. Please can someone explain the difference?

Tuple<int,int> A = new Tuple<int, int>(5,5);
Tuple<int, int> B = new Tuple<int, int>(5, 5);
List<Tuple<int,int>> AList = new List<Tuple<int, int>>() {A};

bool C = AList.Contains(B); // returns true
bool D = A == B; // returns false

Edit 1: To address the duplicate flag. I was aware that == and .Equals were different functions, the surprising thing here is the particular implementation in the List.Contains function.

Upvotes: 4

Views: 2476

Answers (4)

Alexander
Alexander

Reputation: 44

A == B compares references and since they point to two different objects the result is false. I assume this was already familiar to you.

bool C = AList.Contains(B); will call .Equal which checks for equality thus returning true.

The difference is the same as A == B vs A.Equals(B)

Upvotes: 2

uTeisT
uTeisT

Reputation: 2266

That was curious so I took a look as well. When you try

bool D = A.Equals(B);

It returns true which made me to look at C# difference between == and Equals()

Hope this helps

Upvotes: 1

user449689
user449689

Reputation: 3154

Tuples are implemented as reference types, for more info please read here.

The baseline is that for reference type == performs an identity comparison, therefore the result will be true only if both references are pointing to the same object.

The Equals method performs a value comparison and it will return true if the references point to objects that are equivalent.

Upvotes: 3

Jamiec
Jamiec

Reputation: 136074

Contains uses the Equals method inherited from object

== tests for instance equality (ie, are they references to the same exact instance).

Therefore, we can summise that Tuple must override Equals and return true if each of the elements match, whereas == must check that the instances on the left and right hand side are the same.

Upvotes: 1

Related Questions