Interpolated string handler  in c#

Interpolated string handler in c#


Interpolated String Handler in C#

In C#, interpolated strings provide a convenient way to embed variables directly within string literals. This feature, introduced in C# 6, has been enhanced with interpolated string handlers in C# 10, offering more control and efficiency in string creation. This article explores the capabilities and syntax of string interpolation in C#.

Interpolated String C#

String interpolation in C# allows you to include expression values within a string by surrounding them with braces {} and preceding the string with the $ character. This makes the code more readable and easier to write.

String Interpolation C# Example

Here’s a simple example of string interpolation in C#:

 

string name = "Alice";
int age = 30;
string greeting = $"Hello, my name is {name} and I am {age} years old.";
Console.WriteLine(greeting);

C# String Interpolation Escape Quotes

To include a quotation mark inside an interpolated string, you must escape it using the backslash (\) or use double quotes:

 

string quote = $"He said, \"Hello, how are you?\"";
// or
string anotherQuote = $"He said, ""Hello, how are you?""";

C# String Interpolation Format

You can specify the format of the interpolated expressions using standard .NET format strings. This is done by adding a colon : followed by the format specifier inside the interpolation expression:

 

double pi = 3.14159;
string formatted = $"Pi is {pi:F2}";
Console.WriteLine(formatted); // Outputs: Pi is 3.14

C# String Interpolation Escape Curly Braces

To include literal curly braces {} in an interpolated string, you need to double them:

 

string braces = $"{{This will be enclosed in curly braces}}";
Console.WriteLine(braces); // Outputs: {This will be enclosed in curly braces}

C# String Interpolation Multiline

Interpolated strings can span multiple lines, improving readability when constructing long strings:

 

string name = "Alice";
string multiline = $@"Hello, my name is {name}
and I am
writing on multiple lines.";
Console.WriteLine(multiline);

C# String Template

C# doesn't have a built-in string template class like some other languages but using interpolated strings or custom template engines can achieve similar functionality.

C# $ String Operator

The $ operator in C# is used to denote a string literal as an interpolated string, allowing embedded expressions:

 

int x = 10, y = 20;
string result = $"The result of {x} + {y} is {x + y}.";
Console.WriteLine(result);

Interpolated strings in C# make code that constructs strings cleaner and easier to understand. They provide a powerful tool for embedding values and expressions within strings directly, facilitating better readability and maintainability of the code.


 

Leave a reply Your email address will not be published. Required fields are marked*

Categories Clouds