You can look at the difference via a simple example:
void Main()
{
var f = F.Foo;
var b = F.Bar;
}
public class F
{
public const string Foo = "F";
public static readonly string Bar = "B";
}
Will yield the following IL:
IL_0001: ldstr "F"
IL_0006: stloc.0 // f
IL_0007: ldsfld UserQuery+F.Bar
IL_000C: stloc.1 // b
IL_000D: ret
The const
value of Foo
is "baked" at compile to the call site, that is why you see a ldstr
of the value "F" itself, while a static
field emits a ldsfld
, which loads the field at runtime, and then assigned it to the local variable b
.
Making a field both static
and const
is a compile time error. Both const
and static
are defined on the type, not the instance. More so, a static
field can be set at run-time, while const
must be known at compile-time.
If you want to set a bunch of constant values that won't change at run time, going with a const
should be fine. But you have to remember, that if you change a const
value, it isn't enough to compile the source holding the consts, you'll have to re-compile anyone who consumes that const
as well.