Are value types immutable by definition?

后端 未结 12 1523
陌清茗
陌清茗 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:39

    I don't want to complicate reasoning about this by considering ref parameters and boxing. I am also aware that p = p.Offset(3, 4); expresses immutability much better than p.Offset(3, 4); does. But the question remains - aren't value types immutable by definition?

    Well, then you're not really operating in the real world, are you? In practice, the propensity of value types to make copies of themselves as they move between functions meshes well with immutability, but they aren't actually immutable unless you make them immutable, since, as you pointed out, you can use references to them just like anything else.

提交回复
热议问题