After reading a lot about immutability in C#, and understading it's benefits (no side effects, safe dictionary keys, multithreading...) a question has come to my mind:
Why there is not a keyword in C# for asserting that a class (or struct) is immutable? This keyword should check at compile time that there is no way you can mutate the class (or struct). 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 the compiler work would be quite easy, as it would need to check just a few things:
- All public fields are readonly.
- All public properties only have getters.
- All public fields or properties have immutable types as well (simple value types, or immutable classes/structs).
- All public functions or public property getters only depend on immutable fields or properties (public fields/props as described before, or private fields/props which comply to the same restrictions). This of course includes Equals(), GetHashCode() and ToString().
Some possible problems come to my mind with this design:
- For the compiler to know that a compiled class/struct is immutable, it would probably be necesary to make changes in the intermediate language.
- Readonly generic collection (such as
IEnumerable<T>) immutability would depend on the immutability of the type<T>. The proposedimmutablekeyword would not be useful in this context, as you could not declare thatIEnumerable<string>is immutable, even though it is.
Are the reasons stated before enough for this keyword to not exist? Am I missing any other drawbacks? Is this just not necessary enough for such big changes in the language?