Uno.CodeGen
Uno.CodeGen copied to clipboard
EqualityGenerator: Generated code is uncompilable for readonly structs
Hello, very interesting library, thank you :)
I'm submitting a...
Bug report / Feature request
Current behavior
To reproduce, just apply GeneratedEquality
to any readonly struct
. The generated mutable int? _computedHashCode
field is not allowed for readonly struct
s.
Expected behavior
Possible solutions:
- Just recompute the hash on every
GetHashCode
call. - Initialize
_computedHashCode
in the constructor. I don't think this is possible by adding additional members to the struct; would need cooperation from the user's constructor code. - (Bad, but for completeness:) Mark
_computedHashCode
readonly and write to it in an unsafe way.
Complication: There doesn't seem to be a public Roslyn API to detect readonly structs yet: https://github.com/dotnet/roslyn/issues/23792
I have a branch here (I was hesitant to just barge in with a pull request) that resolves the issue by adding an AddHashCodeField
property to GeneratedEqualityAttribute
. If it is false
, _computedHashCode
is not generated and the hash is recomputed on every call to GetHashCode
.
IMHO, this is a useful feature even without the readonly struct
problem because caching the hash code is potentially detrimental to performance if the calculation is just a few arithmetic instructions (since fewer of the objects to be hashed will fit into processor caches).
Minimal reproduction of the problem with instructions
See above
Environment
Nuget Package: Uno.CodeGen
Package Version(s): 1.29.0; master branch
Affected platform(s), Visual Studio: Presumably all platforms and Visual Studio versions that support readonly structs.