🌍 Resource Strings

back

There is a technique in .NET to store translations for button texts. It’s called: Resource Strings. Translations can be stored in resx files and edited in Visual Studio:

Resource String Editor

Contents

File Names

.NET returns the translations in the right language (of the CurrentCulture) if you name your Resource files like this:

Resources.resx
Resources.nl-NL.resx
Resources.de-DE.resx

CultureNames like nl-NL and de-DE are commonly used within .NET.

The culture-independent Resources.resx might be used for the language US English.

Descriptive Names

For clarity it’s recommended to keep the Resource Name descriptive of the text it represents:

Name: Save
Value: "Save"

Name: Save_WithName
Value: "Save {0}"

ResourceFormatters

You could use ResourceFormatters to add the correct values to the {0} placeholders:

public static class ResourceFormatter
{
    public static string Save_WithName(string name) 
        => string.Format(Resources.Save_WithName, name);
}

By using ResourceFormatters, you can ensure the safe usage of placeholders in the code:

ResourceFormatter.Save_WithName("Document");

Returning:

"Save Document"

ResourceFormatterHelper

You can streamline your code and minimize the risk of typos by using the ResourceFormatterHelper from the JJ.Framework:

public static class ResourceFormatter
{
    private static readonly ResourceFormatterHelper _helper 
        = new (Resources.ResourceManager);

    public static string Save => _helper.GetText();

    public static string Save_WithName(string name) 
        => _helper.GetText_WithOnePlaceHolder(name);
}

This eliminates the need to repeat the Resource Name in the code above. It also encourages consistency by forcing the method names to match the Resource Names.

Reusability

JJ.Framework.ResourceStrings goes even further than that. It provides reusable Resources for common phrases like Delete, Edit, Save, and more. No more typing out the same messages over and over again!

Use the Business Layer

Resource strings may play a role beyond just presentation. They’re also commonly used in the business layer. Keeping the DisplayNames for model properties in the business layer makes it possible to reuse them from multiple places.

For More Information

For extra information in Dutch about how to structure the Resource files, see Appendix B.

back