C# Private Const vs Private Readonly – Key Differences Explained

c++constantsreadonly

Is there a difference between having a private const variable or a private static readonly variable in C# (other than having to assign the const a compile-time expression)?

Since they are both private, there is no linking with other libraries. So would it make any difference? Can it make a performance difference for example? Interned strings? Anything similar?

Best Answer

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.