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

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

    Structures are value types.
    Classes are reference types.

    ForEach construct uses IEnumerator of IEnumerable data type elements. When that happens, then variables are read-only in the sense, that you can not modify them, and as you have value type, then you can not modify any value contained, as it shares same memory.

    C# lang spec section 8.8.4 :

    The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement

    To fix this use class insted of structure;

    class MyStruct {
        public string Name { get; set; }
    }
    

    Edit: @CuiPengFei

    If you use var implicit type, it's harder for the compiler to help you. If you would use MyStruct it would tell you in case of structure, that it is readonly. In case of classes the reference to the item is readonly, so you can not write item = null; inside loop, but you can change it's properties, that are mutable.

    You can also use (if you like to use struct) :

            MyStruct[] array = new MyStruct[] { new MyStruct { Name = "1" }, new MyStruct { Name = "2" } };
            for (int index=0; index < array.Length; index++)
            {
                var item = array[index];
                item.Name = "3";
            }
    

提交回复
热议问题