constant - c# static readonly
const string vs. static readonly string in c# (4)
In C#, what's the difference between
static readonly string MyStr;
const string MyStr;
So, it appears that constants should be used when it is very unlikely that the value will ever change, or if no external apps/libs will be using the constant. Static readonly fields should be used when run-time calculation is required, or if external consumers are a factor.
OQ asked about
static string vs
const. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects
private const fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant
static readonly vs
const, then I'd recommend
static readonly for almost all cases because it is more future proof.
When you use a
const string, the compiler embeds the string's value at compile-time.
Therefore, if you use a
const value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.
static readonly string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.
This also means that a
static readonly string can use non-constant members, such as
const string can only be initialized using other constants or literals.
static readonly string can be set in a static constructor; a
const string can only be initialized inline.
Note that a
static string can be modified; you should use
static readonly instead.
You can change the value of a
static readonly string only in the
static constructor of the class or a variable initializer, whereas you cannot change the value of a
const string anywhere.