Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

readonly struct #120

Open
truegoodwill opened this issue Jun 15, 2022 · 3 comments
Open

readonly struct #120

truegoodwill opened this issue Jun 15, 2022 · 3 comments

Comments

@truegoodwill
Copy link

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.

@mcintyre321
Copy link
Owner

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.

@kemsky
Copy link

kemsky commented Mar 7, 2023

@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.

@cremor
Copy link

cremor commented Jul 6, 2023

The initial ask was completed by #129.
But the structs in OneOf.Types could also be made readonly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants