How do I find out if a class is immutable in C#?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
stringis immutable… of course,StringBuilderdoes mutate a string under the bonnet. No, seriously…It is so hard to define immutability given this, let alone robustly detect it…