Consider the Foo struct as follows:
struct Foo
{
public float X;
public float Y;
public Foo(float x, float y)
{
this.X = x;
this.Y = y;
}
public void Change(float x)
{
this.X = x;
}
}
I understand modifying the field in the constructor, that’s perfectly logical to me and my understanding of structs as value, number-like immutable types.
However, since one can‘t do:
Foo bar = new Foo(1, 2);
bar.X = 5;
Why can one use:
Foo bar = new Foo(1, 2);
bar.Change(5);
EDIT: If structs are mutable, then why can’t they be modified when in a list or returned from a property?
You’ve made a key mistaken assumption.
.NET structs are mutable. You can absolutely perform
bar.X = 5;.You should design structs to be immutable, but by the code you have provided, they are mutable.
Have a look at this question for a description of where mutable structs can get your into trouble.
Immutability of structs