c# – Does == and Equals give different results when comparing the same numbers of different types?

Question: Question:

When comparing the same number between int and long, == returns true, but Equals may return false.

Console.WriteLine("1 == 1L: {0}", 1 == 1L);
Console.WriteLine("1L == 1: {0}", 1L == 1);
Console.WriteLine("1.Equals(1L): {0}", 1.Equals(1L));
Console.WriteLine("1L.Equals(1): {0}", 1L.Equals(1));

// 出力:
//   1 == 1L: True
//   1L == 1: True
//   1.Equals(1L): False
//   1L.Equals(1): True

I thought that == and Equals are basically the same for value types, but are they different?

It's also a mystery that it can return true, assuming that only Equals are looking closely at the type.

Answer: Answer:

The Object.Equals(object) is to return the result of operator ==(T, T) if the types are the same, and false if the types are different.
However, in the example of the question sentence, the overload causes an implicit conversion from int to long , and the types in the code do not match.

For the first two expressions, operator ==(long, long) is selected because C # numeric comparisons only define comparisons between int , ulong , long , and uint .
Also, at the end, there is Int64.Equals(long) which is an implementation of IEquatable<T> , so implicit conversion also occurs here.
That is why these results are not False .

Scroll to Top