I have a type object Foo.Foo has Id(int)
Foo
Id
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 questiond) Is it possible that ReferenceEquals(x, y) == true And x.Id != y.Id ?
ReferenceEquals(x, y) == true
x.Id != y.Id
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.
null
object.ReferenceEquals(null, null) - , .
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.
false
true
d: - , - .
, ReferenceEquals() documented true, .
ReferenceEquals()
EDIT: (d): ReferenceEquals true, ; . , - , Id , , . ( , , , , Id, )
ReferenceEquals
, Id, . :
Foo a = new Foo(); Foo b = new Foo();
ReferenceEquals() false a b ( ), allocate Id, , Id .
a
b
,
null == null
if(x!=null && y!=null) return x.id == y.id; return x == null && y == null;
ReferenceEquals , - MSDN "true, objA - , objB , - false". .