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
{
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.