I'm writing a C# app. I'm targeting it to .NET 4.5.1.
There is a translation service in my app, where the translated strings are stored in a database. A string can contain any number of parameters with any type.
string formatString = GetFormatStringFromDB();
Dictionary<string,object> parameters = GetNamedParametersFromSomewhere();
var result = Format(formatString, parameters);
The Composite Formatting syntax looks like an ideal candidate for this.
Like:
string formatString = "{0} is married to {1}, and they have a child of age {2}"; // note that this should still come from the DB
Dictionary<string,object> parameters = GetNamedParametersFromSomewhere();
var result = string.Format(formatString, parameters.Select(o => o.Value)); // I might need to convert this to an array.
What is my problem with this
I want the parameters to be named. I don't want to identify parameters with a numerical index: It's non descriptive and I will most likely confuse/mix them up in translations.
What I want
A syntax where I can represent parameters by their names like:
string formatString = "{wife} is married to {husband}, and they have a child of age {childAge}";
Hey this looks similar to the new String Interpolation syntax in C# vNext! Would I be able to use that?
No:
- It's a vNext feature, I need a solution for .NET 4.5.1.
- It's not even what I need. It's just for inline strings where the parameters - which are already available - get automatically replaced. It can not be stored, and later evaluated for different sets of parameters. Using the new
FormattedStringclass seems way too confusing to me, but it might be a solution although I would need to port it back to the current .NET and I would need some help on that (and also on properly using it).
Also with Composite Formatting it is possible to format a datetime or an int like: "birthday: {0:d}". It's extremely useful for translations as different languages and cultures tend to represent these in quite different formats. I would not want to lose that functionality.
What I ask for here
A syntax I could use. Some functions to feed to parameters to the string and get the result.
Like:
string formatString = GetFormatStringFromDB();
// "Age: {age}, Birthday: {birthday:d}"
Dictionary<string,object> parameters = GetNamedParametersFromSomewhere();
// { "age": (int)10, "birthday": (DateTime)1988-01-01 }
var result = myOwnFormat(formatString, parameters);
//result should be "Age: 10, Birthday: 12/30/2011"
Should I roll my own syntax, and parser for it? Is there something similar already implemented?
EDIT:
I reworded the whole question describing the problem better (hopefully), pointing out what I ask for.