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

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

    What you need to realize is that doing == will always end up calling a method. The question is whether calling == and Equals ends up calling/doing the same things.

    With reference types, == will always 1st check whether the references are the same (Object.ReferenceEquals). Equals on the other hand can be overridden and may check whether some values are equal.

    EDIT: to answer svick and add on SLaks comment, here is some IL code

    int i1 = 0x22; // ldc.i4.s ie pushes an int32 on the stack
    int i2 = 0x33; // ldc.i4.s 
    short s1 = 0x11; // ldc.i4.s (same as for int32)
    short s2 = 0x22; // ldc.i4.s 
    
    s1 == i1 // ceq
    i1 == s1 // ceq
    i1 == i2 // ceq
    s1 == s2 // ceq
    // no difference between int and short for those 4 cases,
    // anyway the shorts are pushed as integers.
    
    i1.Equals(i2) // calls System.Int32.Equals
    s1.Equals(s2) // calls System.Int16.Equals
    i1.Equals(s1) // calls System.Int32.Equals: s1 is considered as an integer
    // - again it was pushed as such on the stack)
    s1.Equals(i1) // boxes the int32 then calls System.Int16.Equals
    // - int16 has 2 Equals methods: one for in16 and one for Object.
    // Casting an int32 into an int16 is not safe, so the Object overload
    // must be used instead.
    

提交回复
热议问题