C# – Integrating phrase translation with String.Format

clocalizationstringtranslation

I have a phrase in English that looks like this: "I have {0} dogs and {1} cats". In code, I provide the data with a String.Format:

String.Format("I have {0} dogs and {1} cats", 1, 2)

So the output is this: "I have 1 dogs and 2 cats".

The problem that I'm trying to solve is the phrase "I have {0} dogs and {1} cats" needs to be translated in other languages.

In this Spanish translation example, the English phrase "I have {0} dogs and {1} cats" and the translated phrase "Tengo {0} perros y gatos {1}" are stored in a database.

If the user were to change "Tengo {0} perros y gatos {1}" to "Tengo {0} perros y gatos {3}", a System.FormatException will be thrown when I call String.Format("Tengo {0} perros y gatos {3}", 1, 2).

For now I'm trapping the format exception and it feels wrong. I'm looking for ideas on a better solution.

Best Answer

Before saving to the database, why not see if you String.Format throws? If so -- do not let the user save.

Just a simple idea that may solve the problem...

Related Topic