Since I’m started programming, I come across terms like const and static read only, which I used randomly based on my mood without even bother about why I am using these. and yesterday I try to find out what is meaning of this in programming grammar. I Google it and find an interesting question on stackoverflow(C#: Static readonly vs const).
const and readonly
The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants.
const must be initialized with value at compile time.
const is by default static and needs to be initialized with constant value, which can not be modified later on. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.
In other words:
- It is useless if the value is fetched at runtime, for e.g. from config
- If we change the value of a const, you need to rebuild all the clients
One thing to note is const is restricted to primitive/value types (the exception being strings)
A Static Readonly type variable’s value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable’s value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.
Public static readonly fields are a little unusual; public static properties (with only a get) would be more common. for e.g.
There are situations where a const and a non-const have different semantics. For example:
The reason is that the method x.Equals has two overloads, one that takes in a short (System.Int16) and one that takes an object (System.Object). Now the question is whether one or both apply with my y argument.
When y is a compile-time constant (literal), the const case, it becomes important that there does exist an implicit conversion from int to short provided that the int is a constant, and provided that the C# compiler verifies that its value is within the range of a short (which 42 is). So both overloads have to be considered. The overload Equals(short) is preferred (any short is an object, but not all object are short). So y is converted to short, and that overload is used. Then Equals compares two short of identical value, and that gives true.
When y is not a constant, no implicit conversion from int to short exists. That’s because in general an int may be too huge to fit into a short. (An explicit conversion does exist, but I didn’t say Equals((short)y), so that’s not relevant.) We see that only one overload applies, the Equals(object) one. So y is boxed to object. Then Equals is going to compare a System.Int16 to a System.Int32, and since the run-time types do not even agree, that will yield false.