Reputation: 29101
The docs for Object.Equals
says that implementors must return false if the parameter is a null reference.
In my class, I'm overriding Equals
to check for value equality. I have a member variable which is similar to the Nullable (T)
structure. My initial inclination is to return True when I'm passed a null reference and my structure's HasValue
property is False.
Is it ever acceptable to return True when the parameter to Equals is a null reference?
EDIT For illustration:
class ExampleClass {
SomeValueType? x;
bool Equals(object other) {
if (other == null) return false; // <-- returns a different value than x.Equals
return x.Equals(other);
}
}
Upvotes: 0
Views: 236
Reputation: 5523
Actually it is not. The equals method cannot return true when two objects are null.
Why?
Well when you define
AnObject obj;
obj is a reference to an object (I am talking for Java but this must be a OO concept)
Object.Equals method takes a parameter which must be an object however null is not an object.
so null.Equals(null) is not an acceptable approach for OO.
Edit:
That's why == operator differs from obj.Equals method. null == null returns true without any headache.
Edit2: It seems that .Net has an inconsistency about Equals method which may be subject to another topic.
int? a = null;
a.Equals(null); // returns true without any problem.
but:
Nullable<T>.Equals
method is defined like this:
Nullable<T>.Equals(object obj):bool
Indicates whether the current Nullable value is equal to a specified object
Since null is not an object, either the documentation or the implementation is not correct.
Upvotes: 1
Reputation: 99939
Nullable<T>.Equals(object)
is the following:
public override bool Equals(object other)
{
if (!this.HasValue)
{
return (other == null);
}
if (other == null)
{
return false;
}
return this.value.Equals(other);
}
So the answer to your question is yes in the case of a struct
(value type) with nullable semantics. If your type is a class
(reference type), the answer is definitely no.
Upvotes: 6