How to make struct fields only modifiable by invoking their members? #96945
Replies: 5 comments 2 replies
-
As a side note, shared static members (especially intentionally mutable ones) are nearly impossible to test with, and if you're using any sort of multithreading/concurrency (any sort of UI, Injecting it as a dependency at least makes it easier to test, although it doesn't absolve you of any concurrency concerns... |
Beta Was this translation helpful? Give feedback.
-
I guess it's not achievable right now, perhaps a new syntax might be needed. |
Beta Was this translation helpful? Give feedback.
-
But what is the problem of using a class? Does you type has to be a struct no matter what? In you example you basically solve the problem by using a class. Shared instance can be modified (because it's a class) but the backing field of "Shared" itself can't. From what I've understood you want "I want this variable to be not directly assignable/readonly but it's contents should be mutable nonetheless". This is what classes can give you. Or am I missing something here? It is harder to do with a struct, something like a wrapper comes to mind. You can then combine ref on an original static field containing a struct and a another ref struct wrapper than acts as a proxy to provide an access to fields/members through refs too but hiding an original field. It is kinda clumsy though. |
Beta Was this translation helpful? Give feedback.
-
I think this belongs on the dotnet/csharplang repo. What you're asking for sounds like controlled-mutability references, which are currently used for An API I can think of which could have used such a feature in the past is |
Beta Was this translation helpful? Give feedback.
-
System.Random
provides a shared instance where we can modify its state by invoking its members. I wrote a lightweight value-typeRandom
, but found it challenging to provide a shared instance. If exposed directly, it could be assigned directly. If exposed through a get accessor, the instance's state cannot be modified. Is there a way to allow access to members of a struct field but disallow direct modification of the field itself?Beta Was this translation helpful? Give feedback.
All reactions