Prerequisite: String Interpolation and Verbatim String
Before C# 8.0 you are allowed to use string interpolation($) and verbatim identifier(@) together but in a specific sequence. It means when you use $ token and @ token together, it is necessary that $ token must appear before the @ token. If you use the @ token before $ token, then the compiler will give you an error, like as shown in the below example:
Example 1:
// C# program to illustrate the use // of interpolated verbatim strings using System; class GFG { // Main Method static void Main() { int Base = 10; int Height = 30; int area = (Base * Height) / 2; // Here, $ token appears before @ token Console.WriteLine( "Finding the area of a triangle:" ); Console.WriteLine($ @"Height = ""{Height}"" and Base = ""{Base}""" ); Console.WriteLine($ @"Area = ""{area}""" ); } } |
Output:
Finding the area of a triangle: Height = "30" and Base = "10" Area = "150"
Example 2:
// C# program to illustrate the use // of interpolated verbatim strings using System; class GFG { // Main Method static void Main() { int Base = 10; int Height = 30; int area = (Base * Height) / 2; // Here, @ token appears before $ token // But the compiler will give an error Console.WriteLine( "Finding the area of a triangle:" ); Console.WriteLine(@ $ "Height = " "{Height}" " and Base = " "{Base}" "" ); Console.WriteLine(@ $ "Area = " "{area}" "" ); } } |
Error:
error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
When we use a @ token before $ token, then the compiler gives an error. This problem is solved in C# 8.0, now you are allowed to use a @ token before $ token or $ token before @ token
$@"..." Or @$"..."
and the compiler will not give an error. As shown in the below example:
Example:
// C# program to illustrate the use // of interpolated verbatim strings using System; namespace Geeks { class GFG { // Main Method static void Main( string [] args) { int Base = 40; int Height = 80; int area = (Base * Height) / 2; Console.WriteLine( "Finding the area of a triangle:" ); // Here, $ token appears before @ token Console.WriteLine($ @"Height = ""{Height}"" and Base = ""{Base}""" ); // Here, @ token appears before $ token Console.WriteLine(@$ "Area = " "{area}" "" ); } } } |
Output:
Finding the area of a triangle: Height = "80" and Base = "40" Area = "1600"