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"

1 comment:

micheal pan said...

BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
you can be to get the new PROGRAMMED blank ATM card that is capable of
hacking into any ATM machine,anywhere in the world. I got to know about 
this BLANK ATM CARD when I was searching for job online about a month 
ago..It has really changed my life for good and now I can say I'm rich and 
I can never be poor again. The least money I get in a day with it is about 
$50,000.(fifty thousand USD) Every now and then I keeping pumping money 
into my account. Though is illegal,there is no risk of being caught 
,because it has been programmed in such a way that it is not traceable,it 
also has a technique that makes it impossible for the CCTVs to detect 
you..For details on how to get yours today, email the hackers on : ( ). Tell your 
loved once too, and start to live large. That's the simple testimony of how 
my life changed for good...Love you all ...the email address again is ;