Constants and static readonly variables, A Comparison

10 Aug 2018 by Kolappan N

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,

Example code
Example code

The above code will be interpreted by the compiler as follows

Complier interpretation
Complier interpretation

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.

Tags: C# View Blog Archive

Loading Comments