Analysis on the Difference between = = and equals and of in C

  • 2021-08-17 00:47:01
  • OfStack

First, look at the following code:


int age = 25; 
short newAge = 25; 
Console.WriteLine(age == newAge); //true 
Console.WriteLine(newAge.Equals(age)); //false 
Console.ReadLine();

int and short are primitive types but return true when compared with "= =" and false when compared with equals (). Why?

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

Specifically:

The primitive type overrides object. Equals (object) of the base class (override) and returns true when object in brackets is the same as its type and value (note that the Nullable type also fits the above judgment; non-empty Nullable types are always boxed into one instance of the base type).

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

In contrast, the "= =" operator is defined as an operation with two shapes (int) or two short shapes (short) or two long shapes (long). When "= =" has two parameters, one is an integer and one is a short integer, the compiler implicitly converts short to int and compares the converted int values.

Other ways to make it work:

The primitive type also has its own equals () method, and equals accepts parameters of the same type.

If you write age. Equals (newAge), the compiler will select int. Equals (int) as the best overload (overload) method and implicitly convert short to int. Then, it returns true, because this method directly compares the sizes of two int values.

short also has an short. Equals (short) method, but the int type cannot be implicitly converted to short, so it is not called.

You can force this method using the cast transformation:

Console. Writeline (newAge. Equals (short) age); //true
This will call short. Equals (short) directly without boxing. If age is greater than 32767, it throws an overflow exception.

You can also call the short. Equals (object) overload, but you need to explicitly pass a boxed object of the same type:
Console.WriteLine(newAge.Equals((object)(short)age)); // true
Like the previous optional method (short. Equals (short)) 1, if the size exceeds the short range, an overflow exception is also thrown. Different from previous solutions, it boxed short into one object-wasting 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, we are not to C # = = and equals () difference to understand, I hope this article to help you learn.


Related articles: