Constants and static readonly variables, A Comparison
There are two ways to create a immutable variables in c#. One is by using static read-only functionality and the other is by using constants. Today we are going to see which approach is better. The main difference between the two is that the static read-only variables are initialized in a constructor while constants are hardcoded by the compiler.
Here is an example to help you understand better,
The above code will be interpreted by the compiler as follows
You can see that the constant is replaced and is no longer a reference. This is the part where they differ fundamentally. Due this nature, const strings are faster as they don’t require any lookup. They offer a slight performance improvement over the static readonly variables.
But you must be careful with constants when using multiple libraries. When you are referencing a constant from an another library the values will be hardcoded and will not be updated when you update in the source library unless you rebuild both of them. Michael has explained this clearly in his blog post.