When do we do GetHashCode() for a Dictionary?

前端 未结 4 564
孤街浪徒
孤街浪徒 2020-12-01 14:44

I have used Dictionary(TKey, TValue) for many purposes. But I haven\'t encountered any scenario to implement GetHashCode() which I believe is because my keys were of primary

4条回答
  •  忘掉有多难
    2020-12-01 15:06

    You have two questions here.

    1. When do you need to implement GetHashCode()
    2. Would you ever use an object for a dictionary key.

    Lets start with 1. If you are writing a class that might possibly be used by someone else, you will want to define GetHashCode() and Equals(), when reference Equals() is not enough. If you're not planning on using it in a dictionary, and it's for your own usage, then I see no reason to skip GetHashCode() etc.

    For 2), you should use an object anytime you have a need to have a constant time lookup from an object to some other type. Since GetHashCode() returns a numeric value, and collections store references, there is no penalty for using an Object over an Int or a string (remember a string is an object).

提交回复
热议问题