Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

== and Equals for Tuple<object>

i have a question why it works like this

var a = new Tuple<object, object, object>(1, 1, 1);
var b = new Tuple<object, object, object>(1, 1, 1);

Console.WriteLine(a.Item1==b.Item1);//Output- False
Console.WriteLine(a.Equals(b));//Output- True
Console.WriteLine(a==b);//Output- False

Why so ?

i try to find some info about how it works, as far as i know this happens because of object type, and value type(int)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That’s the different between value and reference types in C#.

Console.WriteLine(a.Item1==b.Item1);//Output- False

Here you’re comparing two object instances. As for any reference type, the equality operator (unless overriden in that type) does reference comparison.

When you store any value type (e.g. int in your case) in the variable of reference-type (object in your case), you’re doing what’s named boxing.

Console.WriteLine(a.Equals(b));//Output- True

This is because Equals method is overriden in the Tuple type to check if its content are identical to another tuple. It is calling Equals for each of the items and return true if all of them are equal.

Console.WriteLine(a==b);//Output- False

Again, you have two instances of the Tuple class (any class is a reference type), and that Tuple class doesn’t have override for an == operator. Therefore, you’re just checking if those two variables containing the same instance.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading