LibLangly
LibLangly copied to clipboard
LimitedAttribute and Analyzer
limited
is a concept in Ada that applies to a type and declares that the type, after being initialized, can not be reassigned or copied. Furthermore, default equality does not apply to this type, although it is still possible to provide equality definitions if that is still required.
A similar concept would be viable and useful in C#. First however, the use case:
In high performance code, it is important that reassignment does not happen. That is because this puts increased pressure on the garbage collector. Furthermore, this means that state will likely be discarded, a definite and obvious error. Rather, changes to a limited
type are done through mutation, not reassignment.
This poses its own problems however, as mutation is generally not recommended. A solution for this has been worked out and will be in another proposal, based on a pattern I've been using; a new attribute and analyzer will help enforce this pattern.
So how will this vary in C#?
Firstly, type assignment and lifetimes in Ada are radically different from anything in .NET. In .NET reassignment to a struct
is rarely an issue. In Ada, a type may or may not be a reference type based on a number of factors, and even a value type may be passed around by reference in certain situations. Furthermore, reference types in Ada is very different from access types, even though all access types are reference types. Instead of trying to figure out and model this exactly, both struct
and class
can be limited
and will prevent reassignment regardless.
Secondly, there's no point in preventing Equals
or ==
calls for the type, because .NET has reasonable defaults and avoids the complex rules Ada has for equality. While these should be overridden for struct
this isn't an issue of limited
and is more of a performance thing. Other analyzers already cover this case.
This behavior can be enforced purely through an analyzer, and should report an error on violation.