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

前端 未结 7 846
隐瞒了意图╮
隐瞒了意图╮ 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:22

    Value types are called by value. In short, when you evaluate the variable, a copy of it is made. Even if this was allowed, you would be editing a copy, rather than the original instance of MyStruct.

    foreach is readonly in C#. For reference types (class) this doesn't change much, as only the reference is readonly, so you are still allowed to do the following:

        MyClass[] array = new MyClass[] {
            new MyClass { Name = "1" },
            new MyClass { Name = "2" }
        };
        foreach ( var item in array )
        {
            item.Name = "3";
        }
    

    For value types however (struct), the entire object is readonly, resulting in what you are experiencing. You can't adjust the object in the foreach.

    0 讨论(0)
提交回复
热议问题