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

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

提交回复
热议问题