5

I encountered this today, I am sure there is an excellent reason but why is is the case for num2 equal to num1 inconsistent?

long num1 = 1;
int num2 = 1;

num1.Equals(num2);  // TRUE - cool.
num2.Equals(num1); // FALSE - hmm?
num2 == num1; // TRUE - ?! Whit?

Why is this.

John
  • 1,714
  • 21
  • 41

2 Answers2

14
num1.Equals(num2);

resolves to the overload of long.Equals(long) since there is an implicit widening conversion from int to long.

num2.Equals(num1);

calls int.Equals(object) which causes the long num1 to be boxed. Since this is not an int, the comparison returns false.

num2 == num1;

calls the overloaded == operator for long which again causes num2 to be promoted to a long before being compared.

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Yes absolutely, for value type it's not only sufficient to have similar value but types also must be same (or) should be implicit casted. – Rahul Jun 21 '16 at 18:37
  • @Rahul It has nothing to do with whether it's a value or reference type. Pretty much all (good) implementations of equality are defined to only return true for objects of the same type. To not do so is typically a bug in the implementation of `Equals`. – Servy Jun 21 '16 at 18:42
0
long num1 = 1;
int num2 = 1;

MessageBox.Show(num1.Equals(num2).ToString()); 
MessageBox.Show(num2.Equals((int)num1).ToString());
MessageBox.Show((num2 == num1).ToString());

It's a matter of explicitly casting the long as an int to make them equal as expected. The other ones are doing the casting for you.

Ben
  • 26
  • 5