Non-readonly fields referenced in GetHashCode()

前端 未结 2 541
深忆病人
深忆病人 2021-01-17 07:26

Started with overriding concepts and I override the methods Equals and GetHashCode.

Primarily I came up with this \"very simple code\":

2条回答
  •  一向
    一向 (楼主)
    2021-01-17 08:08

    To summarise what was discussed in the comments:

    Hashing is designed to provide a value that doesn't change for a given object, no matter what happens to it - hence it's best to depend only on readonly fields in your GetHashCode method.

    Firstly, I would suggest making the name and lname field readonly, because they probably don't change in your usage scenario.

    As for age, this is something that changes regularly, so probably best to store a DateTime for date of birth, which never changes. Then you can make that readonly too.

提交回复
热议问题