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

Polamin Singhasuwich picture Polamin Singhasuwich · Apr 21, 2016 · Viewed 45.2k times · Source

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

Fabien PERRONNET picture Fabien PERRONNET · Apr 21, 2016

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 supports 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 decimal places:

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

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


SmartFormat.NET for example has 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 described its pros well in his answer.