What should GetHashCode return when object's identifier is null?

前端 未结 3 640
夕颜
夕颜 2021-02-05 04:55

Which of the following is correct/better, considering that identity property could be null.

public override int GetHashCode()
{
    if (ID == null) {
        ret         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 05:20

    It really depends on what you want equality to mean - the important thing is that two equal objects return the same hashcode. What does equality mean when ID is null? Currently your Equals method would have to return true if the ID properties have the same value... but we don't know what it does if ID is null.

    If you actually want the behaviour of the first version, I'd personally use:

    return ID == null ? base.GetHashCode() : ID.GetHashCode();
    

    EDIT: Based on your Equals method, it looks like you could make your GetHashCode method:

    return ID == null ? 0 : ID.GetHashCode();
    

    Note that your Equals(IContract other) method could also look like this:

    return other != null && object.Equals(this.ID, other.ID);
    

    Your current implementation will actually throw an exception if this.ID is null...

    Additionally, your Equals(object) method is incorrect - you shouldn't throw an exception if you're passed an inappropriate object type, you should just return false... ditto if obj is null. So you can actually just use:

    public override bool Equals(object obj)
    {
        return Equals(obj as IContract);
    }
    

    I'm concerned about equality based on an interface, however. Normally two classes of different types shouldn't be considered to be equal even if the implement the same interfaces.

提交回复
热议问题