Replies: 1 comment 1 reply
-
The properties of (normal) Instead, it's more applicable to
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Suppose I have a class with a value type property:
Now, C# sensibly disallow using an object/collection initializer when creating
C
— neithernew C { Property = { Another = 1 } }
ornew C { Property = { 1, 2, 3, 4 } }
compiles, it reports: "CS1918: Members of property 'Property' of type 'S' cannot be assigned with an object initializer because it is of a value type.". That is good, because I'd be modifying the copy returned from the getter.However, if the struct is only a value-type proxy for another object, this error is limiting. Furthermore, if the struct is marked
readonly
, the pitfall this error prevents cannot ever happen. (Same if just theAnother
property /Add(X)
method arereadonly
members, but that's beyond my issue).Is there any change that this limitation could be lifted? Has this been discussed before? I only found a similar issue dotnet/roslyn#29877 about ref properties. Shall I make another one in dotnet/roslyn for this?
Why would I want it?
I'd like to migrate a property from List to a different data structure (an intrusive linked list). Making it possible to replace the List with a readonly struct "ListWrapper" would make the change mostly backwards compatible (on source code level). The only working option I found is to keep the List a reference type, but that defeats the main objective of allocating less objects (it won't get optimized away). It would also work change the property to field, but the same error prevent it from being
readonly
:|In case you'd want to try it, this is a sharplabable snippet with the mentioned options:
Beta Was this translation helpful? Give feedback.
All reactions