I frequently read that struct
s should be immutable - aren\'t they by definition?
Do you consider int
to be immutable?
int i
No, value types are not immutable by definition.
First, I should better have asked the question "Do value types behave like immutable types?" instead of asking if they are immutable - I assume this caused a lot of confusion.
struct MutableStruct
{
private int state;
public MutableStruct(int state) { this.state = state; }
public void ChangeState() { this.state++; }
}
struct ImmutableStruct
{
private readonly int state;
public MutableStruct(int state) { this.state = state; }
public ImmutableStruct ChangeState()
{
return new ImmutableStruct(this.state + 1);
}
}
[To be continued...]