Interpolated Verbatim Strings in C# 8.0
Last Updated :
29 Dec, 2019
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:
using System;
class GFG {
static void Main()
{
int Base = 10;
int Height = 30;
int area = (Base * Height) / 2;
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:
using System;
class GFG {
static void Main()
{
int Base = 10;
int Height = 30;
int area = (Base * Height) / 2;
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:
using System;
namespace Geeks {
class GFG {
static void Main( string [] args)
{
int Base = 40;
int Height = 80;
int area = (Base * Height) / 2;
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 = "80" and Base = "40"
Area = "1600"
Share your thoughts in the comments
Please Login to comment...