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

前端 未结 3 679
夕颜
夕颜 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条回答
  •  Happy的楠姐
    2021-02-05 05:28

    You can simply return 0; , you need to return same HashCode for same values and 0 wont be often returned by ID.GetHashCode() so such Hash function can be pretty ok for any needs. Since your not combining any values (like ID and Name Hashes ) its pretty clear ID is the defining source of HashCode so fixed 0 for Null ID sounds reasonable.

    Otherwise it might be true that your whole approach on GetHashCode override only taking into account ID field is wrong ( and you need to combine several fields to compute hash from them)

    After your edits I can say that second Equals override has too much code , simply replace it with

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

    Your Equals(IContract contract) override appears buggy to me cause only thing defining contract is ID and if IContract has more fields than ID its going to be a bad Equals override.

    PS: Actually if IContract is an interface you probably need to replace your IEquatable to a concrete IEquatable contract because its going to be bad design to be able to return that Different class intstances implementing the same interface are equal cause equality by definition requires to check that objects have the same Type on the first stage of equality check (usually in like 99,9% cases)

提交回复
热议问题