What is the difference between == and Equals() for primitives in C#?

前端 未结 9 902
日久生厌
日久生厌 2020-12-04 05:01

Consider this code:

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


        
9条回答
  •  广开言路
    2020-12-04 05:43

    == In Primitive

    Console.WriteLine(age == newAge);          // true
    

    In primitive comparison == operator behave quite obvious, In C# there are many == operator overload available.

    • string == string
    • int == int
    • uint == uint
    • long == long
    • many more

    So in this case there is no implicit conversion from int to short but short to int is possible. So newAge is converted into int and comparison occurs which returns true as both holds same value. So it is equivalent to:

    Console.WriteLine(age == (int)newAge);          // true
    

    .Equals() in Primitive

    Console.WriteLine(newAge.Equals(age));         //false
    

    Here we need to see what Equals() method is, we calling Equals with a short type variable. So there are three possibilities:

    • Equals(object, object) // static method from object
    • Equals(object) // virtual method from object
    • Equals(short) // Implements IEquatable.Equals(short)

    First type is not case here as number of arguments are different we calling with only one argument of type int. Third is also eliminated as mentioned above implicit conversion of int to short is not possible. So here Second type of Equals(object) is called. The short.Equals(object) is:

    bool Equals(object z)
    {
      return z is short && (short)z == this;
    }
    

    So here condition got tested z is short which is false as z is an int so it returns false.

    Here is detailed article from Eric Lippert

提交回复
热议问题