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

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

    Because there is no overload for short.Equals that accepts an int. Therefore, this is called:

    public override bool Equals(object obj)
    {
        return obj is short && this == (short)obj;
    }
    

    obj is not a short.. therefore, it is false.

提交回复
热议问题