3

I am using .net core 3.1 / C# 8.0. I have two tuples where I expect to have equal values, however the runtime returns inequality. What is wrong with my expectation?

Tuple<decimal, double> firstTuple;
Tuple<decimal, double> secondTuple;

Testing with:

bool tuplesEqualInValue = (firstTuple == secondTuple);

The screenshot shows that the values of firstTuple and secondTuple hold the same values for each item. Yet the first test returns false.

enter image description here

Documentation and other SO posts imply to me that the test should return true: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.3/tuple-equality

https://stackoverflow.com/a/44194321/10340388

https://stackoverflow.com/a/5069777/10340388

Superman.Lopez
  • 1,332
  • 2
  • 11
  • 38

1 Answers1

5

The first two of your links talks about System.ValueTuple, which is not what you are using here (System.Tuple), so they are rather irrelevant for this question. Though, if you are using a C# version that supports them, consider switching over to using ValueTuple instead. Here's a start.

The third link talks about the equality of System.Tuple using .Equals, but you are using ==. If you had used .Equals to compare them, you would see that they are indeed equal:

var firstTuple = Tuple.Create(217930.7650m, 670.556);
var secondTuple = Tuple.Create(217930.7650m, 670.556);
Console.WriteLine(firstTuple.Equals(secondTuple)); // True

Using == doesn't work because unlike, say, string, System.Tuple doesn't overload the == operator, so the default behaviour of comparing the references is used. (string overloads ==)

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thanks, now that I know `Tuple` is a reference type it makes perfect sense for it to return `false`. What's frustrating is that the MS document doesn't make it obvious it is referring to `ValueTuple` instead of `Tuple`... – Superman.Lopez Feb 15 '21 at 06:25
  • @Superman.Lopez [Yes it does](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples#tuples-vs-systemtuple), the page you linked is not actually documentation, it is a proposal by the team – Charlieface Feb 15 '21 at 06:30
  • Indeed, I noticed it only now. It was 1 of the first results in my search. I was not careful enough. – Superman.Lopez Feb 15 '21 at 06:31