String.Format can be extremely useful when you want to concisely show what you are intending to convey, plus it’s essential when strings need to be translated. If your strings have placeholders, the translator can see the context.
One problem with String.Format is that it uses numeric placeholders, which
can sometimes make it difficult to see what they will actually represent.
"Hello {0}" makes it obvious that someone, or something, is
being greeted, but "{0} {1} - {2}" doesn’t give much away.
To alleviate this problem, I made a little utility class called FormatExtensions, which has a method called Format. This accepts a format string with textual placeholders.
Example:
FormatExtensions.Format
(
"You have {balance} in your {account-type} account",
"balance:" + balance.ToString(),
"account-type:" + accountType
);
Now you can take the format string out and give it to your translator, who will no longer have to try to decipher the meaning.
The code is just a rough sketch, but the initial tests I dreamed up
for it seem to suggest it’s working ok. Currently placeholders must
conform to this regular expression: {[A-Za-z][A-Za-z0-9-_]*}
Get the current code here: TextUtils-1.zip
It’s MIT-licensed, as all my open source code is. It’s also tiny and could be implemented better - there are certainly some optimisations which are begging to be done, I’m still not entirely sure about the way I require the arguments to be passed, and there simply aren’t enough tests to be sure it’s bug-free.