Resource files, string.Format, and placeholders in .NET.

As far as I know, the best way to handle dynamic data in a localized string using resource files in .NET is that your localized string in the resources.resx file contains a placeholder in it: Lorem {0} ipsum. and in your code to handle it as follows: string.Format(Resources.My_Localized_Key, myValue);

.

My problems are as follows:

1 / How can I be sure the placeholder is replaced with the actual value? For example, a new developer on your team might have to use this localized string in some new piece of code that they write, but not knowing that they have to feed it some data. No data.

2 / If later, for some reason, the localized string is changed to Lorem {0} ipsum {1}. How can we ensure that all uses of this string in the application are updated?

Is there a better way to handle this? For example, a way to handle these placeholders in a strongly typed way without having to use reflection or having to parse the contents of a localized string ...? Or is this just a way to do it?

+3


source to share


2 answers


In practice, level 1 developers are unlikely to reuse a string without checking its contents, and if they did, they would probably notice the placeholder when they run their code (or QA). So it is unlikely and will not be the end of the world.

For problem 2, you can use "Find Usage" in Visual Studio on the auto-generated property it creates for the resource to find every location it used and make sure the desired number (and order) of parameters exists everywhere it used. But generally speaking, resource strings are not reused much (in fact, it is not recommended to reuse localizable text in different contexts, as the translation may need to be changed in different contexts, for example, due to language rules or space constraints).



Another risk I see is that the translator might omit or corrupt placeholders, which would be more difficult to detect. But that would be just one example of a localization error ... There are many other things that can go wrong when an application is localized, and there is often no reliable way to protect them.

+1


source


I think you can write your own custom tool for Visual Studio (http://www.codeproject.com/Articles/31257/Custom-Tools-Explained) that generates a resource class from a resx file and uses it instead of the default one. In your tool, you can parse the localized string, and if it has placeholders, you can generate a method instead of a property Resources.My_Localized_Key

. The method might look like Resources.My_Localized_KeyFormat(object param)

with the appropriate number of parameters according to the number of placeholders.

But this is just an idea and I have not implemented it myself (but I have implemented my own tool for generating code for resx files and it works fine).



Or you can use F #, which checks the parameters against its version of string.Format at compile time.

0


source







All Articles