Are value types immutable by definition?

后端 未结 12 1517
陌清茗
陌清茗 2020-12-04 09:18

I frequently read that structs should be immutable - aren\'t they by definition?

Do you consider int to be immutable?

int i         


        
12条回答
  •  半阙折子戏
    2020-12-04 09:26

    You can write structs that are mutable, but it is best practice to make value types immutable.

    For instance DateTime always creates new instances when doing any operation. Point is mutable and can be changed.

    To answer your question: No, they are not immutable by definition, it depends on the case if they should be mutable or not. For instance, if they should serve as dictionary keys, they should be immutable.

提交回复
热议问题