C# difference between == and Equals()

前端 未结 17 1405
走了就别回头了
走了就别回头了 2020-11-21 06:56

I have a condition in a silverlight application that compares 2 strings, for some reason when I use == it returns false while .Equals()

17条回答
  •  失恋的感觉
    2020-11-21 07:40

    ==

    The == operator can be used to compare two variables of any kind, and it simply compares the bits.

    int a = 3;
    byte b = 3;
    if (a == b) { // true }
    

    Note : there are more zeroes on the left side of the int but we don't care about that here.

    int a (00000011) == byte b (00000011)

    Remember == operator cares only about the pattern of the bits in the variable.

    Use == If two references (primitives) refers to the same object on the heap.

    Rules are same whether the variable is a reference or primitive.

    Foo a = new Foo();
    Foo b = new Foo();
    Foo c = a;
    
    if (a == b) { // false }
    if (a == c) { // true }
    if (b == c) { // false }
    

    a == c is true a == b is false

    the bit pattern are the same for a and c, so they are equal using ==.

    Equal():

    Use the equals() method to see if two different objects are equal.

    Such as two different String objects that both represent the characters in "Jane"

提交回复
热议问题