Friday 18 December 2015

String interpolation in C# 6

With C# 6 we can finally wave goodbye to the cumbersome, C-style way of injecting values into a string. Before, target string and arguments were separated and indexes were used to place the right argument at the right place inside the string. That was an error prone process.

var id = 123;
var name = "abc";
var s = string.Format("id = {0}, name = {1}", id, name);

New interpolation syntax allows direct injection of variables into the string:

var id = 123;
var name = "abc";
var s = $"id = {id}, name = {name}";

It is possible to inject string result of some more complex expressions:

var task = new Task();
var taskExceptionReport = 
   $"Task.Exception: {((task.Exception == null) ? "null" : task.Exception.ToString())}";

Further reading:
Interpolated Strings (MSDN)
Bill Wagner: "A Pleasant New C# Syntax for String Interpolation"

No comments: