class string is immutable. It is impossible implementing an immutable struct type as you can't disable or override assignment operation (=). Even you define a readonly struct, you can always change the value of the struct type by using assignment operator.
For example, x,y are values of a readonly struct. x = y; will change the content of x. So, the readonly struct section in C# language reference is not correct. Is this right?
Jaish MathewsPosted Nov 24, 2024, 8:05 AM
You are correct in observing that the
readonly structdoes not prevent reassignment. This is by design:readonly structonly ensures that the fields of the struct cannot be directly modified.In above defined structure, if you create references as
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Then
p1.X = 100; // Invalidp1 = p2; // Valid. Entirely replaces the instance, not its fields.
To create true immutability, you can try:
readonly struct.readonlyfield or property to hold the struct ifield n a class.So, the implementation should be different using a class and your program only use that class to acess the structure.
Then
var holder = new ImmutableStructHolder(new Point(1, 2)); //Valid
holder.PointValue = new Point(3, 4); // Error: Cannot assign to readonly field.
Leo QiaoPosted Nov 24, 2024, 10:29 PM
Thank you for great response. That is what I meant.