Thoughts on Immutable Types

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.

  1. Create an ImmutableAttribute:

      [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class, Inherited = false, AllowMultiple = false)]

      sealed class ImmutableAttribute : Attribute { }

  1. Put it on your struct:

      [Immutable]

      struct S

      {

            readonly int x;

      }

  1. Write an FxCop rule that verifies immutability.

What does the FxCop rule look for?

  1. All fields must be marked ‘readonly’.

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