I18N – A lack of resources

Today I’d like to show provide you with some tips for resource files in C#.NET. If you don’t know what the header means, have a look at this link. TL;DR: It’s about localisation of applications.

Resource filesĀ (ending with *.resx) are used to define various resource for different languages in a regular C# project. This can be simple strings but also pictures, for instance. I will talk about strings today. You can – of course – assign a string to a variable when you need it. But you should not. Maybe you need the string in various places, and then you realise, that you have to change it. Trust me: more than once, you will miss at least one occurrence. That’s why I prefer to define all the strings I need as constants (except log messages) and use them whenever they are required. However, those instances never are strings that are intended for the user’s eye, but file names, identifiers and so on.

Let’s say that I’d liek to assign the following text to a (WinForms) label that will be shown in my UI:

Although I could introduce a constant for this text, ReSharper tells me to extract this text into a resource file. Via its quick fix action (alt + enter) I choose to move the text and name it USER_LABEL. ReSharper will automatically create a new Resources.resx file – if it does not exist – and will store the value This text is obviously visible for the user for the key USER_LABEL in this very file. So far, so good. My code now looks like this:

Hovering the mouse over USER_LABEL will show me a tooltip that contains the text that is stored for this property.

But that is still the same language, there is no translation (yet). At first, I’ll copy the *.resx file and paste it in the same folder (this is done within Visual Studio). I’ll rename the copy to Resources.de.resx, for my German translation, and all I need to do now is to open the file and to adjust the translation for the label. Visual Studio will create a so-called satellite assembly for every language that is defined via a separate resource file. Depending on the language that is set in the application, either the English (default) or the German file is used.

Sometimes it is necessary to have a line break in your strings. However, you cannot simply write \n or \n\r at the desired position, you have to press Shift+Enter to force a line break.

In addition, you can add variables to your strings and fill them during runtime. I’ll show you how that works. Let’s have a look at the following string which is stored for PRODUCT_ADVERTISEMENT in the resource file:

Then I can fill this string in my code with values for product name and date via the method string.Format like this:

By using resource files, I’ve got pretty much as many possibilities with strings as I have with constants or variables. I can, however, apply additional translations without having to adjust my code.

Leave a Reply

Your email address will not be published. Required fields are marked *