简体   繁体   中英

Is it ever acceptable to return True when the parameter to Equals is a null reference?

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); 
    }
}

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM