Reputation: 2951
I am thinking of converting a C# application currently in English, to support multiple languages.
The application uses interpolated strings a lot - e.g. $"Short Name {header.ShortName} already exists"
. These strings will need to be translated into other languages.
I have been recommended to use .resx files to hold strings in different languages, but don't see how they would work with interpolated strings. Some of the strings have multiple variables in them to make a sentence, and languages with different word order (e.g. German) would probably need the variables in different places in the sentence.
Can anyone advise on how to deal with this? Is the only option to remove interpolated strings altogether, or write an alternative implementation that can get its basic template string from a resx?
Upvotes: 1
Views: 71
Reputation: 91
You might want to use placeholders in resource Strings instead of directly embedding the variables inside the string, which can later be replaced with values at runtime. For example, in your .resx file, you would write:
English: ShortNameAlreadyExists = "Short Name {0} already exists"
Spanish: ShortNameAlreadyExists = "Nombre corto {0} ya existe"
Then use string.Format to put the variable in the place of string where it goes. Can be in the middle like English or Spanish or in any other place if using German for example.
var localizedString = string.Format(Resources.ShortNameAlreadyExists, header.ShortName);
This can be use for as many variables as you like using {0}, {1} ...
Hope this helps.
Upvotes: 0
Reputation: 822
You can use the currently recommended way of localizing in .NET, which is IStringLocalizer
.
Here's IStringLocalizer
overview, and here's additional info on how to use it with parametrized strings.
In your resource files you can store strings with placeholders in different places, then provide the placeholder values with parameters.
Resources/Program.en.resx
HelloPerson: Hello, {name}!
Resources/Program.pl.resx
HelloPerson: {name}, witaj!
public class LocalizationExample(IStringLocalizer<LocalizationExample> localizer)
{
public void ShowLocalizedString()
{
var text = localizer["HelloPerson", new { Name = "John" }];
Console.WriteLine(text);
}
}
Upvotes: 3