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 MathewsRank #225 · 11K reputationPosted Nov 24, 2024, 3:05 AM EST
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.readonly struct Point { public readonly int X { get; } public readonly int Y { get; } public Point(int x, int y) { X = x; Y = y; } }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.
class ImmutableStructHolder { public readonly Point PointValue; public ImmutableStructHolder(Point point) { PointValue = point; } }Then
var holder = new ImmutableStructHolder(new Point(1, 2)); //Valid
holder.PointValue = new Point(3, 4); // Error: Cannot assign to readonly field.
Leo Qiao115 reputationPosted Nov 24, 2024, 5:29 PM EST
Thank you for great response. That is what I meant.