C# 10- Constant String Interpolation

What is string interpolation?

C# String interpolation was introduced in C#6, which allows to use the variable into string also it’s a method of concatenating, formatting and manipulating strings.

Syntax of string interpolation:

{<interpolationExpression>[,<alignment>][:<formatString>]} 

interpolationExpression –  The expression that produces a result to be formatted

alignment– The constant expression whose value defines the minimum number of characters in the string representation of the expression result. If positive, the string representation is right-aligned; if negative, it’s left-aligned.

formatString– A format string that is supported by the type of the expression result

Click here to read more about formatString.

Example:

string message = "Welcome";
string displayMsg = $"Hello {message} !";
Console.WriteLine(displayMsg);

Constant String Interpolation:

From C#10, we can use string interpolation to initialize constant string. One of the constraint is all the expression used for a placeholder should be a constant string.

As per the above statement, the below example will not work, you will get compile time error.

Constant String interpolation constraint

 Example:

 This example works because the expression used for a placeholder is a constant.

Constant string interpolation

Reference:

$ – string interpolation – C# reference | Microsoft Docs

gowthamk91

Leave a Reply

%d