Guaranteed immutability in C #

After reading a lot about immutability in C # and understanding its advantages (no side effects, safe dictionary keys, multithreading ...), the following occurred to me:

Why is there no keyword in C # to say that a class (or structure) is immutable? This keyword should be checked at compile time so that you cannot mutate the class (or structure). For example:

public immutable class MyImmutableClass
{
    public readonly string field;

    public string field2; //This would be a compile time error

    public readonly AnyMutableType field3; //This would be a compile time error


    public string Prop { get; }

    public string Prop2 { get; set; } //This would be a compile time error

    public AnyMutableType Prop3 { get; } //This would be a compile time error
}

I think that working with the compiler will be quite simple, since only a few things will need to be checked:

  • All public fields are read-only.
  • All public properties have only recipients.
  • All public fields or properties also have immutable types (simple value types or immutable classes / structures).
  • ( /, , /, ). , , Equals(), GetHashCode() ToString().

:

  • , / , , .
  • (, IEnumerable<T>) <T>. immutable , , IEnumerable<string> , .

, , , ? ? ?

+6
1

: , , , , , .

, , , readonly - .

. , [ImmutableObject(true)], , , ... .

"readonly structs" # ( ref locals, Span<T> ..) - : . , ref readonly , this struct.

+4

All Articles