views:

68

answers:

2

Before .NET, we had our own phrase localization system and we built in a way for comments to be nested in the formatting string like: "{0:price}". I'm finding that I miss this more and more as the years go by.

It doesn't appear that there is a way to document formatting strings in situ like this in .NET:

string.Format("{0//numerator} / {1//denominator} = {2//ratio}"
              ,somevar
              ,anothervar
              ,yetanothervar);

In particular this is useful in localization/phraseology where the insertion points get reordered, without changing the code:

string.Format("Dividing {1//denominator} into {0//numerator} gives {2//ratio}"
              ,somevar
              ,anothervar
              ,yetanothervar);

Anyone have any tricks they use to document these to avoid mistakes when terms get rearranged in maintenance/localization etc?

The reason that the commenting is important is that for localization and configuration, typically, the string is not in the code with the variables - I have had them in resource files, in the app.config and in databases.

In an actual example, a subclassed control exposes a PhraseID property (controls are mapped to IDs in an XML file generated from the form, and the form controls are translated on the fly), so the subclassed form does something like this:

// Handle the phrases without insertion points - this is in the base class
foreach (Control in this.Controls) {
    IXLatable ixl = (IXLatable) Control;
    ixl.Text = GetPhrase(ixl.PhraseID);
}

// in the individual form classes, they override the behavior for complex displays:
lnkPublish.Text = string.Format(GetPhrase(lnkPublish.PhraseID), filename, foldername, userid);

Where the dictionary contains default and localized string like:

phraseid, language code, phrase
1,en,"{0//filename} published to {1//foldername} by {2//userid}"
1,pl,"{2//userid} ublishedpay ethay ilefay {0//filename} otay {1//foldername}"

It is a lot less likely that a translator (who never sees the source code) will get the indexes wrong if they are provided with comments in the default phrase. And easier for a non-localized speaker to troubleshoot problems in a translated resource.

+2  A: 

In your example naming the variables something meaningfull, will have the same affect as the comments.

AndreasN
That turns out not to be the case in non-trivial examples.
Cade Roux
+2  A: 

You could look at Phil Haack's NamedFormat extension, which allows you to use formats like

NamedFormat("{{{foo}}}", new {foo = 123})
Jon Galloway
I'm happy with positional usage, but that's interesting. I imagine worse runtime issues are possible with named usage.
Cade Roux