Search code examples
c#stringresource-file

How can I avoid using magic strings when using ResourceManager.GetString()?


I have a resource file in a Class Library project. I'm using this resource file to hold various messages the user may end up seeing.

For example, the name of the resource is "InvalidEmailAddress" and the value in the en-US resource file is "Invalid Email Address".

When I call the ResourceManager's GetString(string) method I am doing this:

 return resourceManager.GetString("InvalidEmailAddress");

However, this seems really bad to me. What if somebody changes the name of the resource? Now my statement will return a null value.

Is there a way around this issue?

UPDATE: Localization is an important factor here. The resource manager is used in order to ensure I can change the culture and get appropriate string values.


Solution

  • You can instead use an automatically generated class - the magic string constants will be removed from the code and replaced with strongly typed access methods. VS names this file ResourceName.Designer.cs and updates it every time resx is modified in VS.

    Sample of a generated method:

       internal static string String1 {
            get {
                return ResourceManager.GetString("String1", resourceCulture);
            }
    

    Note: while creating this file is the default behavior when you add a new resource in VS, you may have disabled it or you may have tried to use the generated resource outside the assembly. In that case, make sure to set the "Custom Tool" property or resx file to "PublicResXFileCodeGenerator" or "ResXFileCodeGenerator" (later if you use resources only inside a single assembly). (Thanks @dbaseman for comment).