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:
Some possible problems come to my mind with this design:
IEnumerable<T>
) immutability would depend on the immutability of the type <T>
. The proposed immutable
keyword would not be useful in this context, as you could not declare that IEnumerable<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?
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.
Mutable and immutable are English words meaning "can change" and "cannot change" respectively. The meaning of the words is the same in the IT context; i.e. a mutable string can be changed, and. an immutable string cannot be changed.
Immutability allows you to track the changes that happen to these objects like a chain of events. Variables have new references that are easy to track compared to existing variables. This helps in debugging the code and building the concurrent application.
The short version would be: because nobody has proposed, spec'd, designed, implemented, tested, documented, translated and supported that feature.
The longer version would relate to why to do it, given that it can be achieved indirectly with the readonly
field - what benefit would it add.
For classes, it turns out to be relatively minor. Note that there is an [ImmutableObject(true)]
attribute that can be used, but no features or frameworks really have a use for it, so ... nobody uses it.
There was a proposal to add "readonly structs" in a future version of C# (related to ref
locals, Span<T>
, etc) - but: it died a death and evaporated. However, the ref readonly
stuff lives on, which is intended to prevent reassignment of this
in struct
instance methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With