Constants and static readonly variables, A Comparison

Aug 10, 2018 by Kolappan N

There are two ways to create a variables with fixed values in C#. One is by using static read-only functionality and the other is by using constants. This blog post explains the difference between those two.

The main difference between the two is that the static read-only variables are initialized in a constructor during runtime while constants are hardcoded by the compiler.

Here is an example to help you understand better,

public void TestMethod(){
    string first = Model.StaticReadOnly;
    string second = Model.Constant;
}

The above code will be interpreted by the compiler as follows

public void TestMethod(){
    string first = Model.StaticReadOnly;
    string second = "This is a constant";
}

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.

This also means that any variable that gets initialized during the runtime cannot be a constant, as constants need to have their value at compile time. For example, a user input which does not change cannot be a constant but can be a readonly variable.