Why does Microsoft advise against readonly fields with mutable values?

前端 未结 7 902
予麋鹿
予麋鹿 2020-12-28 12:34

In the Design Guidelines for Developing Class Libraries, Microsoft say:

Do not assign instances of mutable types to read-only fields.

7条回答
  •  旧巷少年郎
    2020-12-28 13:05

    Microsoft has a few such peculiar advices. The other one that immediately springs to mind is not to nest generic types in public members, like List>. I try to avoid these constructs where easily possible, but ignore the newbie-friendly advice when I feel the use is justified.

    As for readonly fields - I try to avoid public fields as such, instead going for properties. I think there was a piece of advice about that too, but more importantly there are cases now and then when a field doesn't work while a property does (mostly it has to do with databinding and/or visual designers). By making all public fields properties I avoid any potential problems.

提交回复
热议问题