Search code examples
c#resourcesconstantsresx

Declare a const string from a resource


When I declare a const from a resx I have a compilation error.

private const string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");

I understand why this compilation message occurs but is there a trick to declare a const from a resource?


Solution

  • That's because a const must be a compile time constant. Quoting the MSDN documentation:

    Constants are immutable values which are known at compile time and do not change for the life of the program.

    From https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants

    In your case the value is coming from a method invocation. So the result may not be known at the time of compilation. The reason for this is that the constant value is directly replaced into the IL code.

    In fact, when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces.

    So instead of const, you can use a static readonly here:

    private static readonly string ERROR_MESSAGE = MyResource.ResourceManager.GetString("resx_key");