I\'ve read around about const
and static readonly
fields. We have some classes which contain only constant values. They are used for various things
Constants are like the name implies, fields which don't change and are usually defined statically at compile time in the code.
Read-only variables are fields that can change under specific conditions.
They can be either initialized when you first declare them like a constant, but usually they are initialized during object construction inside the constructor.
They cannot be changed after the initialization takes place, in the conditions mentioned above.
Static read-only sounds like a poor choice to me since, if it's static and it never changes, so just use it public const. If it can change then it's not a constant and then, depending on your needs, you can either use read-only or just a regular variable.
Also, another important distinction is that a constant belongs to the class, while the read-only variable belongs to the instance!
A static readonly field is advantageous when exposing to other assemblies a value that might change in a later version.
For instance, suppose assembly X
exposes a constant as follows:
public const decimal ProgramVersion = 2.3;
If assembly Y
references X
and uses this constant, the value 2.3
will be baked into assembly Y
when compiled. This means that
if X
is later recompiled with the constant set to 2.4, Y
will still
use the old value of 2.3 until Y
is recompiled. A static
readonly field avoids this problem.
Another way of looking at this is that any value that might change in the future is not constant by definition, and so should not be represented as one.
Another difference between declaring const and static readonly is in memory allocation.
A static field belongs to the type of an object rather than to an instance of that type. As a result, once the class is referenced for the first time, the static field would "live" in the memory for the rest of time, and the same instance of the static field would be referenced by all instances of the type.
On the other hand, a const field "belongs to an instance of the type.
If memory of deallocation is more important for you, prefer to use const. If speed, then use static readonly.
I would use static readonly
if the Consumer is in a different assembly. Having the const
and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.
const int a
readonly int a
The readonly
keyword is different 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, while a const
field is a compile-time constant, the readonly
field can be used for runtime constants
Short and clear MSDN reference here