In C#, why can't I modify the member of a value type instance in a foreach loop?

前端 未结 7 897
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 11:37

I know that value types should be immutable, but that\'s just a suggestion, not a rule, right? So why can\'t I do something like this:

struct MyStruct
{
             


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 12:06

    It's a suggestion in the sense that there's nothing stopping you from violating it, but it should really be afforded much more weight than "it's a suggestion". For instance, for the reasons you're seeing here.

    Value types store the actual value in a variable, not a reference. That means that you have the value in your array, and you have a copy of that value in item, not a reference. If you were allowed to change the values in item, it would not be reflected on the value in the array since it's a completely new value. This is why it isn't allowed.

    If you want to do this, you'll have to loop over the array by index and not use a temporary variable.

提交回复
热议问题