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

前端 未结 9 880
日久生厌
日久生厌 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

    Equals() is a method of System.Object Class
    Syntax : Public virtual bool Equals()
    Recommendation if we want to compare state of two objects then we should use Equals() method

    as stated above answers == operators compare the values are same.

    Please don't get confused with ReferenceEqual

    Reference Equals()
    Syntax : public static bool ReferenceEquals()
    It determine whether the specified objects instance are of the same instance

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-04 05:45

    For value types, .Equals requires the two objects to be of the same type and have the same value, while == just tests if the two values are the same.

    Object.Equals
    http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx

    0 讨论(0)
提交回复
热议问题