DEV Community

loading...

Interpolated strings in C#

Joe Enos
Software developer/architect, mostly working with .NET and SQL Server.
・1 min read

C# now has a better alternative to string.Format - interpolated strings. This makes it much easier to build a formatted string, without worrying about indexes.

The syntax is very simple - just a dollar sign before the open quotation mark.

string name = "world";
WriteLine($"Hello {name}");
Enter fullscreen mode Exit fullscreen mode

Double-up your braces to get literal braces:

WriteLine($"Hello {name}, your choices are: {{ A, B, C }}");
Enter fullscreen mode Exit fullscreen mode

Use a colon just like you would with string.Format to format a number or date:

WriteLine($"The time is {DateTime.Now:HH:mm}");
Enter fullscreen mode Exit fullscreen mode

Use both the @ and $ characters to do an interpreted and verbatim string at the same time.

string tableName = "Users";
WriteLine(@$"
    SELECT * FROM {tableName}
    WHERE UserID = 1;
");
Enter fullscreen mode Exit fullscreen mode

Use parentheses if your expression is a ternary expression - this makes it clear that the colon is part of the ternary expression, not to declare the formatting.

bool success = true;
WriteLine($"Was it successful? {(success ? "Yes" : "No")}");
Enter fullscreen mode Exit fullscreen mode

Use a comma and a number to pad your data - a negative number will left-align your text, and a positive number will right-align it.

var people = new[] {
     new { Name = "Mookie", Age = 49 },
     new { Name = "Shrek", Age = 7 }
};

WriteLine($"{"Name",-12}|{"Age",3}");
foreach (var person in people)
{
    WriteLine($"{person.Name,-12}|{person.Age,3}");
}
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
yugely profile image
yugely

If it wasn't for Microsoft, I'd be a happy C#/F#/Powershell developer. But, seeing cool features brings me back to the day