How to include Variables in Localized Strings?

DTI-Matt picture DTI-Matt · Jun 8, 2012 · Viewed 11.2k times · Source

I'm trying to display a message to the user along the lines of:

"User 5 could not be added"

But how can I add variables to a string that is being placed in a .resx file? I've trying searching for things like "Variables in Localization" "Globalization with Variables" etc, but came up dry.

If I weren't localizing I would write:

Console.Write("User " + userNum + " could not be added");

How can this be accomplished with resources?

Answer

Oded picture Oded · Jun 8, 2012

You can't do this directly.

What you can do is place a token - a specific string that can be replaced with string.Replace with the value of the variable.

A good candidate for this would be the built in string formatting:

Console.Write(string.Format("User {0} could not be added", userNum));

Assuming userNum has the value 5, the result would be:

User 5 could not be added

You can localize this string with the composite format specifiers.