How do I find out if a class is immutable in C#?
There is ImmutableObjectAttribute
, but this is rarely used and poorly supported - and of course not enforced (you could mark a mutable object with [ImmutableObject(true)]
. AFAIK, the only thing this this affects is the way the IDE handles attributes (i.e. to show / not-show the named properties options).
In reality, you would have to check the FieldInfo.IsInitOnly
, but this only applies to truly 100% immutable types (assuming no reflection abuse, etc); it doesn't help with popsicle immutability, nor things that are immutable in practice, but not in their implementation; i.e. they can't be made to be publicly mutable, but in theory the object supports it.
A classic example here would be string... everyone "knows" that string
is immutable... of course, StringBuilder
does mutate a string under the bonnet. No, seriously...
It is so hard to define immutability given this, let alone robustly detect it...