Byte Friendly

Random thoughts on programming and related topics.

Formatting With Named Parameters

| Comments

Problems with formatting

The “official” way to format strings in .NET BCL is to use String.Format method (and wrappers for it, like Console.Write).

image

This is not very reliable method. You can forget to include parameter into the format string or confuse one parameter with another. And your IDE does not offer any help here.

We want better way!

People feel that this is not right and try to invent some more convenient methods. One of which is formatting with named parameters (using names instead of ordinals). Yesterday I read this blog post. There are several implementations of formatting with named parameters and author makes more reliable and efficient implementation just for fun. But you know what? It still doesn’t seem right.

image

Anonymous type here is supposed to protect us from renaming issue, but it clutters the code. And again, we do not get any help from IDE (warnings about non-existing elements, highlighting, etc).

But how can it be done even better?

Let’s look at Nemerle. It borrows “spliced string” syntax from languages like PHP (“hello, $username”). But it has several advantages over PHP and Perl. All expressions are resolved and typed at compile-time. And if you use VS package, then you’ll get development-time checks (on-the-fly) and highlighting.

One picture is worth a thousand words. So look at these code samples

image

image

Feel the difference! What can possibly go wrong here (except for NullReferenceException, but string.Format is also vulnerable to it). Also, this code is very efficient. Essentially it is transformed to a series of string.Concat or StringBuilder.Append calls.

P.S.: One more thousand-words-picture.

image

Comments