Are value types immutable by definition?

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

    No, value types are not immutable by definition.

    First, I should better have asked the question "Do value types behave like immutable types?" instead of asking if they are immutable - I assume this caused a lot of confusion.

    struct MutableStruct
    {
        private int state;
    
        public MutableStruct(int state) { this.state = state; }
    
        public void ChangeState() { this.state++; }
    }
    
    struct ImmutableStruct
    {
        private readonly int state;
    
        public MutableStruct(int state) { this.state = state; }
    
        public ImmutableStruct ChangeState()
        {
            return new ImmutableStruct(this.state + 1);
        }
    }
    

    [To be continued...]

提交回复
热议问题