Jason Baker Jason Baker - 3 months ago 6
C# Question

Named string formatting in C#

Is there any way to format a string by name rather than position in C#?

In python, I can do something like this example (shamelessly stolen from here):

>>> print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2}
Python has 002 quote types.


Is there any way to do this in C#? Say for instance:

String.Format("{some_variable}: {some_other_variable}", ...);


Being able to do this using a variable name would be nice, but a dictionary is acceptable too.

Answer

There is no built-in method for handling this.

Here's one method

string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);

Here's another

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

A third improved method partially based on the two above, from Phil Haack