readonly struct
truegoodwill opened this issue · 3 comments
Since all fields of the OneOf struct are readonly, can we also mark the struct readonly using the keyword in its declaration?
I was surprised to discover this has not already happened and suspect you have a good reason. I'm looking to improve performance in method calls by passing the struct with the in
keyword.
I haven't really used readonly
before so I'm unsure of pros/cons of adding it. Anyone able to provide more informations on risks/downsides? If there are none, I would happily accept a PR.
@mcintyre321, you can read more here: https://devblogs.microsoft.com/premier-developer/avoiding-struct-and-readonly-reference-performance-pitfalls-with-errorprone-net/
tldr; if struct is not readonly
then compiler must create defensive copies in some cases to maintain semantics, most notably when you have readonly
field:
private readonly OneOf<MyStruct1, MyStruct2> _value = new MyStruct1();
In the example above _value
is copied each time you call Match
or any other method that is not marked as readonly
to ensure that _value
does not change.