Is there a difference between private const and private readonly variables in C#?

Well, you can use consts in attributes, since they exist as compile time. You can’t predict the value of a static readonly variable, since the .cctor could initialize it from configuration etc.

In terms of usage, constants are burnt into the calling code. This means that if you recompile a library dll to change a public constant, but don’t change the consumers, then he consumers will still use the original value. With a readonly variable this won’t happen. The flip of this is that constants are (very, very slightly) quicker, since it simply loads the value (rather than having to de-reference it).

Re interning; although you can do this manually, this is most commonly a compiler/runtime feature of literals; if you init a readonly field via a literal:

someField = "abc";

then the "abc" will be interned. If you read it from config, it won’t be. Because a constant string must be a literal, it will also be interned, but it is accessed differently: again, reading from the field is a de-reference, rather than a ldstr.

Leave a Comment