[Proposal] Allow readonly reference (in
) when unboxing
#3028
Replies: 5 comments
-
I think the error message is definitely confusing. It's probably worth opening an issue on Roslyn to fix it. You could even fix it yourself - it's extremely easy to do. As for allowing this: |
Beta Was this translation helpful? Give feedback.
-
@YairHalberstadt You are generally correct, but I'd view this more like leveraging certain restrictions rather than adding a brand new feature. It's obvious this feature was added back when readonly references weren't possible (as the message suggests), but now that they're here, this seems natural to follow. Just for information, what is the workaround for getting the reference without copying? As for its use, let's say you have an object (perhaps obtained via reflection) that stores a large structure, or perhaps the structure isn't so large but the unboxing happens many times. It's possible in some cases there is a better solution (like not using a struct), but I can imagine sometimes there isn't much to do. |
Beta Was this translation helpful? Give feedback.
-
@IllidanS4 |
Beta Was this translation helpful? Give feedback.
-
The workaround is to make your struct implement an interface, then cast the box to the interface type. Looks like you might be able to use |
Beta Was this translation helpful? Give feedback.
-
yeah at the moment do |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Currently, the result of an unboxing conversion is a value, not a variable. Consequently, when an attempt is made to obtain the reference to the result, an error is generated. However, the error message suggests an
in
reference might work. It doesn't:The error message is factually incorrect, as a readonly reference (
in
) cannot be used to modify the value of the object, and so no modification happens and no modification could ever happen (as far as C# is concerned).I think that, in the spirit of improving performance considering value types, being able to directly access the value of the object without having to copy it would be beneficial. Moreover,
unbox.any
already provides a reference (which is stated to be read-only in the specification), soin
fits that well.Moreover, copying the value in some additional cases is also unnecessary. Currently, calling a method on a
readonly
struct copies the value even though no modifications are guaranteed (but obtaining the value of a field doesn't copy the whole struct), and in the future, calling areadonly
method (per this proposal) also seems to be plausible without copying.Beta Was this translation helpful? Give feedback.
All reactions