It's the symbol that allow you to create a interpolated string, it's a new feature from C# 6, and I love it.
Also its a Syntax Sugar, I will explain what it mean in the end.
Lets see in action. look the following code
public string Receive(int value)
{
return String.Format("Received: {0}", value);
}
public string Receive6(int value)
{
return $"Received: {value}";
}
What happens what it is compiled
They will have the same IL implementation, look here the IL(in Debug mode, not optimized) from Receive
.method public hidebysig instance string Receive (int32 'value') cil managed
{
// Method begins at RVA 0x22d4
// Code size 22 (0x16)
.maxstack 2
.locals init (
[0] string
)
IL_0000: nop
IL_0001: ldstr "Received: {0}"
IL_0006: ldarg.1
IL_0007: box [mscorlib]System.Int32
IL_000c: call string [mscorlib]System.String::Format(string, object)
IL_0011: stloc.0
IL_0012: br.s IL_0014
IL_0014: ldloc.0
IL_0015: ret
} // end of method Program::Receive
Now lets see IL(in Debug mode, not optimized) from Receive6
.method public hidebysig instance string Receive6 (int32 'value') cil managed
{
// Method begins at RVA 0x22f8
// Code size 22 (0x16)
.maxstack 2
.locals init (
[0] string
)
IL_0000: nop
IL_0001: ldstr "Received: {0}"
IL_0006: ldarg.1
IL_0007: box [mscorlib]System.Int32
IL_000c: call string [mscorlib]System.String::Format(string, object)
IL_0011: stloc.0
IL_0012: br.s IL_0014
IL_0014: ldloc.0
IL_0015: ret
} // end of method Program::Receive6
As you can see with your own eyes, the IL is pretty much the same.
Now lets understand what is a Syntax Suggar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
From https://en.wikipedia.org/wiki/Syntactic_sugar
So instead to write the massive string.Format
, use string interpolation, the compiler will work for you and convert the syntax that you wrote, in another code, in this case, using string.Format
.
Can I use formatting options like in string.Format?
Yes, you can, look below
public static string Receive(int value)
=> string.Format("Received: {0, 15:C}", value);
public static string Receive6(int value)
=> $"Received: {value,15:C}";
Console.WriteLine(Receive(1));
Console.WriteLine(Receive6(1));
Console.WriteLine($"Current data: {DateTime.Now: MM/dd/yyyy}")
Output (my culture is pt-br)
Received: R$ 1,00
Received: R$ 1,00
Current data: 01/01/2016
Obs.: I would like to mention, there is not performance difference, since using string interpolation e string.Format is exactly the same thing