What I want to achieve:
A container which contains a bunches of value type fields.
The container has the following characteristics
- Acts like POD.
- Mutable
- Could be copied by value.
- Fields of the container will keep growing in the future.
For letting it could be copied, my attempt is using MemberwiseClone()
which would shallow copy the container.
So a class containing only value type fields might work, but MemberwiseClone()
could be broken once the class contains a reference type while MemberwiseClone()
copy the reference.
My intent is to prevent inexperienced developers from accidentally breaking the system.
Expected answer:
Some kind of attribute node [AllowOnlyValueTypeFields] on a class to allow the compiler to check it.
[AllowOnlyValueTypeFields] class foo { int[] bar; // beep! compiled failed. }
- Maybe... a design pattern might solve it?
Current workaround:
- A unit test using reflection and check every field of the container.
- A "rule" about not using reference type in this container and soon become forgotten.
Search keywords:
- C# field property only value type
- C# field property allow only value type
- C# force only value type field stackoverflow
None of the above got meaningful results.
Any suggestion is appreciated.