1

What I want to achieve:

A container which contains a bunches of value type fields.

The container has the following characteristics

  1. Acts like POD.
  2. Mutable
  3. Could be copied by value.
  4. 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:

  1. Some kind of attribute node [AllowOnlyValueTypeFields] on a class to allow the compiler to check it.

    [AllowOnlyValueTypeFields]
    class foo {
        int[] bar; // beep! compiled failed.
    }
    
  2. Maybe... a design pattern might solve it?

Current workaround:

  1. A unit test using reflection and check every field of the container.
  2. A "rule" about not using reference type in this container and soon become forgotten.

Search keywords:

  1. C# field property only value type
  2. C# field property allow only value type
  3. C# force only value type field stackoverflow

None of the above got meaningful results.

Any suggestion is appreciated.

8
  • 1
    Mutable structs are a bad design. Commented Jun 19, 2020 at 2:56
  • 1
    "Fields of the container will keep growing in the future." - struct is not recommended to be over 16 bytes. So there goes your design
    – T.S.
    Commented Jun 19, 2020 at 2:57
  • @T.S. My intent is get a bunch of parameters lazy copy easily. I may just alter the struct to class, but still using MemberwiseClone for copy. Is there a better way to lazy copy everything? Serialization comes to my mind. Is it a bit overhead?
    – Louis Go
    Commented Jun 19, 2020 at 3:00
  • @LouisGo You edited the question to use "class" instead of "struct" but you missed a few occurrences so I removed them for you. Feel free to edit the post further or roll the edit back if it doesn't reflect your intent.
    – 41686d6564
    Commented Jun 19, 2020 at 3:23
  • I believe the answer is "no" and unit test is best you can get... You may want to further clarify the question if you want to limit your type to blittable types or want to support string too for example... The question stackoverflow.com/questions/10574645/… may simplify your unit test check if blittable is what you are looking for. Commented Jun 19, 2020 at 3:55

0

Browse other questions tagged or ask your own question.