If you use a C# struct, it should be immutable. Mutable structs cause all kinds of nasty problems; don’t do it. If I had to design the C# language over, I’d say that mutable structs would have to be marked with the ‘mutable’ keyword.
If you want to follow the pattern of making your stucts immutable, here’s one way to do it.
- Create an ImmutableAttribute:
- Put it on your struct:
- Write an FxCop rule that verifies immutability.
What does the FxCop rule look for?
- All fields must be marked ‘readonly’.
- Fields must be either a built-in type or must have the Immutable attribute.
What do you think? Does my scheme seem workable? Is the result valuable?
Edit1: From a comment: see also ValueObject on the wiki.
Edit2: From a comment: for this to work, you need to be able to place the attribute on classes as well.