user33540 user33540 - 1 year ago 55
C# Question

Is there a "String.Format" that can accept named input parameters instead of index placeholders?

This is what I know

str = String.Format("Her name is {0} and she's {1} years old", "Lisa", "10");

But I want something like

str = String("Her name is @name and she's @age years old");
str.addParameter(@name, "Lisa");
str.addParameter(@age, 10);

Answer Source

In C# 6 you can use string interpolation :

string name = "Lisa";
int age = 20;
string str = $"Her name is {name} and she's {age} years old";

As Doug Clutter mentioned in his comment, string interpolation also support format string. It's possible to change the format by specifying it after a colon. The following example will output a number with a comma and 2 decimals place :

var str = $"Your account balance is {balance:N2}"

As Bas mentioned in his answer, string interpolation doesn't support template string. Actually, it have no built in support for that. Fortunatly it exist some great libraries.

SmartFormat.NET for example has a support for named placeholder :

Smart.Format("{Name} from {Address.City}, {Address.State}", user)

// The user object should at least be like that 

public class User
    public string Name { get; set; }
    public Address Address { get; set; }

public class Address
    public string City { get; set; }
    public string State { get; set; }

It is available on NuGet.

Mustache is also a great solution. Bas has well described it's pros in his answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download