In our application, we have some lines coming from the translation, which may contain variables. For example, the Can i have a {beverage}?part {beverage}should be replaced by a variable. My current implementation works by having a dictionary of the name and values โโof all variables and just replacing the correct line. However, I would like to register the variables by reference, so if the value always changes, the resulting string also changes. Normally passing a parameter with a keyword refmight do the trick, but I'm not sure how to store them in a dictionary.
TranslationParser:
static class TranslationParser
{
private const string regex = "{([a-z]+)}";
private static Dictionary<string, object> variables = new Dictionary<string,object>();
public static void RegisterVariable(string name, object value)
{
if (variables.ContainsKey(name))
variables[name] = value;
else
variables.Add(name, value);
}
public static string ParseText(string text)
{
return Regex.Replace(text, regex, match =>
{
string varName = match.Groups[1].Value;
if (variables.ContainsKey(varName))
return variables[varName].ToString();
else
return match.Value;
});
}
}
main.cs
string bev = "cola";
TranslationParser.RegisterVariable("beverage", bev);
Console.WriteLine(TranslationParser.ParseText("Can i have a {beverage}?"));
bev = "fanta";
Console.WriteLine(TranslationParser.ParseText("Can i have a {beverage}?"));
Is this possible at all, or am I just getting the problem wrong? I am afraid that the only solution would be unsafe code (pointers).
, , . ref.