The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string. – see documentation webpage.
In this tutorial, I will show you how can use this feature.
First, let’s see the basic example program for show a string:
1 2 3 4 5 6 7 8 9 | using System; public class Program { public static void Main() { Console.WriteLine("Hello World"); } } |
If I want to use a string variable then the source code in C# will be this:
1 2 | string this_world = "this world"; Console.WriteLine("Hello {0}", this_world); |
The result is this: Hello this world.
The string interpolation uses the $ sign and lets you interpolate the this_world into this way:
1 | Console.WriteLine($"Hello {this_world}"); |
This embedding the variable string within the string.
If you use the dotnetfiddle online tool then you need to use the Roslyn compiler.
This is very useful because can be used like this:
1 | Console.WriteLine($"Hello {this_world.ToUpper()}"); |
I can use many variables:
1 2 3 | string this_world = "this world"; string another_world = "ANother world"; Console.WriteLine($"Hello {this_world.ToUpper()} and {another_world.ToLower()}"); |
Using a var like a item, see bellow:
1 2 | var item = (nickname:"catafest", height: "1.66m"); Console.WriteLine($"Hello {item.nickname}"+$". Height is {item.height}"); |
The result is this:
1 | Hello catafest. Height is 1.66m |
Also, I can check the value with executing logic:
1 2 | int price = 5; Console.WriteLine($"Price is {(price < 4 ? "good": "not good")}"); |
The result is:
1 | Price is not good |