SoFunction
Updated on 2025-03-06

A brief analysis of the difference between == and equals in C#

First look at the following code:

int age = 25; 
short newAge = 25; 
(age == newAge); //true 
((age)); //false 
();

int and short are primitive types, but return true with "==" comparison, and equals() comparison returns false.Why?

In short: "equals()" is more complicated than "==".

Specifically:

The original type overrides the object of the base class and returns true when the object in the parentheses is the same as its type and value (note that the Nullable type is also suitable for the above judgment; non-empty Nullable types are always boxed into an instance of the base type).

Since newAge is short, (object) returns true when object is short and the value is equal to newAge value. What you are passing is an int object, so it returns false.

In contrast, the "==" operator is defined as an operation with two shaping (int) or two short (short) or two long (long). When the two parameters of "==" are shaped and the other are short, the compiler will implicitly convert short to int and compare the converted int value size.

Other ways to make it work:

Primitive types also have their own equals() method, which accepts parameters of the same type.

If you write (newAge), the compiler will select (int) as the best overload method and implicitly convert short to int. It will then return true, because this method directly compares the size of two int values.

Short also has a (short) method, but the int type cannot be implicitly converted to short, so it will not be called.

You can force this method using cast conversion:

(((short)age)); //true
This will be called directly (short), without boxing operations. If the age is greater than 32767, it will throw an overflow exception.

You can also call (object) this overload, but you need to explicitly pass a boxed object of the same type:
(((object)(short)age)); // true
Like the previous optional method ((short)), if the size exceeds the short range, an overflow exception is also thrown. Unlike previous solutions, it boxs short into an object—a waste of time and memory.

Here is the Equals() used in practice:

public override bool Equals(Object obj) { 
    if (!(obj is Int16)) {
      return false; 
    } 
    return m_value == ((Int16)obj).m_value; 
  } 
  public bool Equals(Int16 obj) 
  { 
    return m_value == obj; 
  }

Through this article, do you have any understanding of the difference between == and equals() in C#? I hope this article will be helpful to everyone's learning.