1

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)

2
  • 4
    You realise that the first compare has nothing to do with tuples? As you are comparing two boxed ints? maybe you want to read this: learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/… Commented Mar 22, 2024 at 20:09
  • 3
    It's 2024 now. Tuple has been mostly obsolete since C# 7 came out more than 6 years ago... especially Tuple<object ... >. Instead, this should really be a ValueTuple<int, int, int>, which you can define like this: var a = (1, 1, 1); Commented Mar 22, 2024 at 20:37

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

FYI you seem to have mixed up what the line Console.WriteLine(a.Equals(b)); is actually comparing. You seem to think its comparing ints and not the tuples.
@RandRandom right, my bad. Corrected the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.