I’ve been reading a bit about immutable structures such as string. Simply put, they don’t change state once they’ve been created (so for instance asking for a substring gives you a new string).
Now, I was wondering whether the CLR “knows” that a certain type is immutable, and uses this fact to do something clever at runtime, or is immutability mainly something that makes certain scenarios simpler to program?
In general the CLR doesn’t do anything special with immutable types. They are treated in the same way as any other types.
For strings there is special support. Strings can be interned and reused. In C#, source code string literals are automatically interned by the compiler. You can also intern a string yourself by calling
String.Intern.