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
:
.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
.
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}"
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"
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
.
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!
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 extra information in Dutch about how to structure the Resource
files, see Appendix B.