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.
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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments