1

I'm trying to collect all string declarations in my app in a single class, so that they are easy to modify project-wide. I can create a Strings class like so:

public static class Strings
{
    public static readonly string Title = "App Title";
}

or like so:

public static class Strings
{
    public const string Title = "App Title";
}

The class should be static and all the properties constant. What difference does it make whether the properties of Strings have the static readonly or the const keywords in them?

transporter_room_3
  • 2,583
  • 4
  • 33
  • 51

1 Answers1

2

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.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321