Does null == null?

I have a type object Foo.
Foo has Id(int)

a) Is the code below β€œgood”?
 b) What should I return if both values ​​are zero?

// overload operator ==
public static bool operator ==(Foo a, Foo b)
{
    if (ReferenceEquals(x, y))
    {
        return true;
    }

    if (x == null && y == null)
    {
        return // ??? 
    }

    if (x == null || y == null)
    {
        return false; 
    }

    return x.Id == y.Id; // Ids are the same
}

public static bool Equals(Foo x, Foo y)
{
   return x == y;
}

EDIT:
c) If the Equals method calls the == operator or vice versa?

Last question
d) Is it possible that ReferenceEquals(x, y) == true And x.Id != y.Id ?

+5
source share
4 answers

Yes

null is nothing more than an internal pointer with a value of 0. Thus, this is a comparison of two links that have a zero value.

object.ReferenceEquals(null, null) - , .

if (ReferenceEquals(x, y))
{
    return true;
}

if (x == null && y == null) // THIS CHECK IS REDUNDANT!!!
{
    return true;
}

== Equals , :

        object s1 = 2;
        object s2 =  1+1;

        Console.WriteLine(s1 == s2);
        Console.WriteLine(s1.Equals(s2));

false true.

d: - , - .

+7

, ReferenceEquals() documented true, .

EDIT: (d): ReferenceEquals true, ; . , - , Id , , . ( , , , , Id, )

, Id, . :

Foo a = new Foo();
Foo b = new Foo();

ReferenceEquals() false a b ( ), allocate Id, , Id .

+13

,

null == null

if(x!=null && y!=null)
   return x.id == y.id;
return x == null && y == null;
+4

ReferenceEquals , - MSDN "true, objA - , objB , - false". .

+3

All Articles