A New Way of Passing References: Allowing Use of References Without Direct Modification #7842
Replies: 4 comments 5 replies
-
It should be theoretically achievable by a custom attribute with analyzer. What's the benefit of having this built in with the language? Note that static struct fields are allocated on the heap. |
Beta Was this translation helpful? Give feedback.
-
Side note: don't start with syntax when proposing features, as different people may interpret them differently. Even |
Beta Was this translation helpful? Give feedback.
-
Would this work any differently to how ref readonly works now?
|
Beta Was this translation helpful? Give feedback.
-
Another case that this would solve: #4345. using (var tempList = new PoolBackedList<int>(0))
{
FillList(ref tempList); // Error, cannot pass using variable by reference.
} P.S. Syntax may not be important at this point, but I think |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I recently encountered two issues that seem to point to the same language feature requirement.
In this example,
s_shared
is returned by reference to allow external access to its members for modification of its state. However, this also allows external modification ofs_shared
directly like thisS.Shared = default
, which is not what I want.In this example, I want to add some extension methods for types that implement a specific interface. However, I don't know whether the types implementing the interface are value types or reference types, so I have to implement them separately for each case, even though the final invocation calls the same internal implementation.
In both examples, I only want to use references and do not want to directly modify the referenced variables. However, since
ref
allows modification of the referenced variables, it poses a security risk in the first example, and the second example cannot merge extension methods applicable to value types with those applicable to reference types.If there is a way to pass references that signifies you can only use this reference without modifying it, both of these issues can be resolved. The specific syntax can be discussed; here, I'm using
using ref
temporarily to explain some details.using ref
in the syntax ensures that the referenced variable will not be directly modified. At runtime, ifT
is a value type,using ref T p
is equivalent toref T p
; ifT
is a reference type,using ref T p
is equivalent toT p
. With such syntax, we can update the two examples mentioned at the beginning:With
using ref
, when passing references, we should useusing ref
whenever possible, unless we genuinely intend to modify the referenced variable. This can make our code more adaptable becauseref
can be converted tousing ref
, but the reverse is not possible.Beta Was this translation helpful? Give feedback.
All reactions