When do we do GetHashCode() for a Dictionary?

前端 未结 4 563
孤街浪徒
孤街浪徒 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 should override Equals and GetHashCode whenever the default Object.Equals (tests for reference equality) will not suffice. This happens, for example, when the type of your key is a custom type and you want two keys to be considered equal even in cases when they are not the same instance of the custom type.

    For example, if your key is as simple as

    class Point {
        public int X { get; set; }
        public int Y { get; set; }
    }
    

    and you want two Points two be considered equal if their Xs are equal and their Ys are equal then you will need to override Equals and GetHashCode.

提交回复
热议问题