For this post in my series, I want to look at one of my favorite little time savers, String Interpolation. String Interpolation is basically when you put tokens into a string and those are replaced for you by the language. Previously, in C#, we might do one of the following things:
// Concatenation var name = "Pete"; var greeting = "Hello, " + name;
// String Format var name = "Pete"; var greeting = string.Format("Hello, {0}", name);
Sometimes, with a long string with a lot of tokens, this can get kind of unwieldy. And, if you reuse tokens (say, a line break, or the person’s name), it can be almost impossible to keep things straight. Other languages have had features like this for awhile.
Swift:
var name = "Pete" var greeting = "Hello, \(name)"
Ruby:
name = "Pete" greeting = "Hello #{name}"
Now, in C# 6, we get that kind of clarity as well. The syntax calls for you to use a dollar sign ($) in front of the string and then use curly braces surrounding the variable reference in the string. Here is an example
New C# 6 String Interpolation:
var name = "Pete"; var greeting = $"Hello, {name}";
In my opinion, that beats the pants off of string.Format(). Additionally, you can also reference class properties by the same syntax. Here is another example:
var name = "Pete"; var greeting = $"Hello, {name}. Your name has {name.Length} letters.";
You can also express values from methods:
var items = new []{"a", "b", "c"}; Console.WriteLine($"Items has {items.Count()} items");
So, there you go. I can promise you that I’m going to use this instead of string.Format() in every project that is running the necessary framework versions.
One thing that bit me with this is that this the newer C# features don’t seem to be available in Razor (yet?).
Matt,
I was able to get this to work a few ways in Razor using VS2015 and an MVC6 project.
I was able to do this
@Html.Raw($"{Environment.MachineName}")
and also define the variable like this:
@{
var machineName = $"{Environment.MachineName}";
}
and then just @machineName to get it to show up in line. I couldn’t just @ and then do it but by using the Html.Raw() or an intermediate variable, I was good. Maybe you can try that?