Contagious Read-Only Type #7791
Replies: 2 comments 4 replies
-
|
Beta Was this translation helpful? Give feedback.
-
This sounds an awful lot to me like |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
This sounds an awful lot to me like |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Typically, a type needs to restrict intentions that modify its state, but no need to restrict intentions that read its state. Therefore, we often write some read-only properties and methods. However, these read-only properties and methods should not return references to fields, as that would be unsafe. To address this, we have to clone fields or write more properties and methods to provide details about fields. In fact, if we can constrain callers to only access read-only members of returned references, there is no need to do these extra steps.
So, I came up with the concept of Read-only Type. Note that this is unrelated to
readonly struct
and is also unrelated toreadonly class
(which currently does not exist). Consider this example:Here,
readonly List<Item>
acts as a type that includes all the read-only members ofList<Item>
. But at runtime, it is equivalent toList<Item>
.More details (Edit: there are some changes later on):
As you can see, read-only type has a contagious nature, ensuring safety.
Perhaps it can go even further by directly exposing fields without the need for properties, something like this:
<<<<<<<<<< EDIT >>>>>>>>>>
Due to the contagious nature of read-only types, the key is how to construct the first read-only type, without having to change our programming approach. We can continue to use
readonly
to mark certain properties and methods, as we do now (with the need to add support forclass
), indicating "this property or method will not modify this object." Then, we need to create the first read-only type. Here is the updated example.Note that a read-only type is returned here, which is different from the meaning of a
readonly
property. The read-only contagion starts from this return value. If we modifyList<T>
like this:then we can start contagion:
We haven't caused any breaking changes. We can still use
List<T>
as before; the difference is that now, we can access itsreadonly
members throughreadonly List<T>
.Beta Was this translation helpful? Give feedback.
All reactions