Search code examples
.netstructclrvalue-type

What are good uses for mutable structs?


So I know that mutable structs/value types are considered 'evil' in .Net. So why is it possible to make them? What are some good uses for mutable structs that justify adding the feature to the CLR in the fist place?


Solution

  • An excellent question! Personally, I'm definitely not a fan, however some people running on things like CF/XNA will swear blind that they need the extra bit of performance they can eek from (over)using structs, which generally involves them being mutable. This argument has some value if the struct is accessed directly in an array, on a public field, or accessed via ref, but in many cases you might get bitten by chomping through stack-space by duplicating an over-sized struct many times on the stack.

    If you are using structs, mutable-or-not, and if you are using serialization, then a fully immutable struct can be a real problem. Partial or "popsicle" immutability can be an answer here, but the same frameworks that are tempting for value-types also tend to have more reflection restrictions, making private/field-based serialization tricky. So mutable is handy.

    All of the above are really examples of using a struct to hold something that is actually better classified as an object. Pure values don't change. Ever. So full immutability is fine.

    As a final thought... not a justification for the existence, but it makes excellent interview fodder, and is great for tripping up the unwary. Maybe it was designed by people acting as consultants ;p