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

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

提交回复
热议问题