Search code examples
c#.net-3.5string-formatting

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.


Solution

  • 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


    Update: This is now built-in as of C# 6 (released in 2015).

    String Interpolation

    $"{some_variable}: {some_other_variable}"