首页 > 其他分享 >String interpolation using $

String interpolation using $

时间:2024-10-18 23:11:24浏览次数:1  
标签:use Console String interpolated C# using interpolation string

The $ character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, the compiler replaces items with interpolation expressions by the string representations of the expression results.

String interpolation provides a more readable, convenient syntax to format strings. It's easier to read than string composite formatting. The following example uses both features to produce the same output:


var name = "Mark";
var date = DateTime.Now;


// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.

Beginning with C# 10, you can use an interpolated string to initialize a constant string. You can do that only if all interpolation expressions within the interpolated string are constant strings as well.

Structure of an interpolated string
To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal.

The structure of an item with an interpolation expression is as follows:
{[,][:]}
Elements in square brackets are optional. The following table describes each element:

The following example uses optional formatting components described in the preceding table:


Console.WriteLine($"|{"Left",-7}|{"Right",7}|");

const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI,FieldWidthRightAligned} - default formatting of the pi number");
Console.WriteLine($"{Math.PI,FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Output is:
// |Left   |  Right|
//     3.14159265358979 - default formatting of the pi number
//                3.142 - display only three decimal digits of the pi number

Beginning with C# 11, you can use new-lines within an interpolation expression to make the expression's code more readable. The following example shows how new-lines can improve the readability of an expression involving pattern matching:


string message = $"The usage policy for {safetyScore} is {
    safetyScore switch
    {
        > 90 => "Unlimited usage",
        > 80 => "General usage, with daily safety check",
        > 70 => "Issues must be addressed within 1 week",
        > 50 => "Issues must be addressed within 1 day",
        _ => "Issues must be addressed before continued use",
    }
    }";

Interpolated raw string literals
Beginning with C# 11, you can use an interpolated raw string literal, as the following example shows:


int X = 2;
int Y = 3;

var pointMessage = $"""The point "{X}, {Y}" is {Math.Sqrt(X * X + Y * Y):F3} from the origin""";

Console.WriteLine(pointMessage);
// Output is:
// The point "2, 3" is 3.606 from the origin

To embed { and } characters in the result string, start an interpolated raw string literal with multiple $ characters. When you do that, any sequence of { or } characters shorter than the number of $ characters is embedded in the result string. To enclose any interpolation expression within that string, you need to use the same number of braces as the number of $ characters, as the following example shows:


int X = 2;
int Y = 3;

var pointMessage = $$"""{The point {{{X}}, {{Y}}} is {{Math.Sqrt(X * X + Y * Y):F3}} from the origin}""";
Console.WriteLine(pointMessage);
// Output is:
// {The point {2, 3} is 3.606 from the origin}

In the preceding example, an interpolated raw string literal starts with two $ characters. You need to put every interpolation expression between double braces ({{ and }}). A single brace is embedded into a result string. If you need to embed repeated { or } characters into a result string, use an appropriately greater number of $ characters to designate an interpolated raw string literal. If the string literal has more repeated braces than the number of $ characters, the { and } characters are grouped from inside to outside. In the preceding example, the literal The point {{{X}}, {{Y}}} interprets {{X}} and {{Y}} as interpolated expressions. The outer { and } are included verbatim in the output string.

Special characters
To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}". For more information, see the Escaping braces section of the Composite formatting article.

As the colon ( " : " ) has special meaning in an interpolation expression item, to use a conditional operator in an interpolation expression. Enclose that expression in parentheses.

The following example shows how to include a brace in a result string. It also shows how to use a conditional operator:


string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Output is:
// He asked, "Is your name Horace?", but didn't wait for a reply :-{
// Horace is 34 years old.

An interpolated verbatim string starts with both the $ and @ characters. You can use $ and @ in any order: both $@"..." and @$"..." are valid interpolated verbatim strings. For more information about verbatim strings, see the string and verbatim identifier articles.

Culture-specific formatting
By default, an interpolated string uses the current culture defined by the CultureInfo.CurrentCulture property for all formatting operations.

To resolve an interpolated string to a culture-specific result string, use the String.Create(IFormatProvider, DefaultInterpolatedStringHandler) method, which is available beginning with .NET 6. The following example shows how to do that:


double speedOfLight = 299792.458;

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = $"The speed of light is {speedOfLight:N3} km/s.";

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = string.Create(
    specificCulture, $"The speed of light is {speedOfLight:N3} km/s.");

string messageInInvariantCulture = string.Create(
    System.Globalization.CultureInfo.InvariantCulture, $"The speed of light is {speedOfLight:N3} km/s.");

Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
// Output is:
// nl-NL      The speed of light is 299.792,458 km/s.
// en-IN      The speed of light is 2,99,792.458 km/s.
// Invariant  The speed of light is 299,792.458 km/s.

In .NET 5 and earlier versions of .NET, use implicit conversion of an interpolated string to a FormattableString instance. Then, you can use an instance FormattableString.ToString(IFormatProvider) method or a static FormattableString.Invariant method to produce a culture-specific result string. The following example shows how to do that:


double speedOfLight = 299792.458;
FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);
Console.WriteLine(messageInSpecificCulture);
// Output:
// The speed of light is 2,99,792.458 km/s.

string messageInInvariantCulture = FormattableString.Invariant(message);
Console.WriteLine(messageInInvariantCulture);
// Output is:
// The speed of light is 299,792.458 km/s.

For more information about custom formatting, see the Custom formatting with ICustomFormatter section of the Formatting types in .NET article.

Other resources
If you're new to string interpolation, see the String interpolation in C# interactive tutorial. You can also check another String interpolation in C# tutorial. That tutorial demonstrates how to use interpolated strings to produce formatted strings.

Compilation of interpolated strings
Beginning with C# 10 and .NET 6, the compiler checks if an interpolated string is assigned to a type that satisfies the interpolated string handler pattern. An interpolated string handler is a type that converts the interpolated string into a result string. When an interpolated string has the type string, it's processed by the System.Runtime.CompilerServices.DefaultInterpolatedStringHandler. For the example of a custom interpolated string handler, see the Write a custom string interpolation handler tutorial. Use of an interpolated string handler is an advanced scenario, typically required for performance reasons.

Note

One side effect of interpolated string handlers is that a custom handler, including System.Runtime.CompilerServices.DefaultInterpolatedStringHandler, may not evaluate all the interpolation expressions within the interpolated string under all conditions. That means side effects of those expressions may not occur.

Before C# 10, if an interpolated string has the type string, it's typically transformed into a String.Format method call. The compiler can replace String.Format with String.Concat if the analyzed behavior would be equivalent to concatenation.

If an interpolated string has the type IFormattable or FormattableString, the compiler generates a call to the FormattableStringFactory.Create method.

C# language specification
For more information, see the Interpolated string expressions section of the C# language specification and the following new feature specifications:

C# 10 - Improved interpolated strings
C# 11 - Raw string literals
C# 11 - New-lines in string interpolations
See also
C# special characters
Strings
Standard numeric format strings
Composite formatting
String.Format
Simplify interpolation (style rule IDE0071)
String interpolation in C# 10 and .NET 6 (.NET blog)

标签:use,Console,String,interpolated,C#,using,interpolation,string
From: https://www.cnblogs.com/DesertCactus/p/18475207

相关文章

  • 【C++】string类(1)
    ......
  • java 11天 StringBuffer static
    补充:1--100正则表达式1-100 100拿出去或上“[1-9][0-9]{0,1}|100”0--100  0和100拿出去或上“[1-9][0-9]{0,1}|100|0”获取常量池中的地址 String - intern();String学过23个 一.StringBufferStringBuffer 字符串长度+16 StringBuffer空间是2*oldCap......
  • C++ -string -常见用法2
    博客主页:【夜泉_ly】本文专栏:【C++】欢迎点赞......
  • BigDecimalUtil工具类 Java 多种类型(Double, String, Integer)转换成BigDecimal 进行加
    工具说明没有什么太复杂的代码。先是通过方法名称确定返回值的类型(BigDecimal、Double、String)。然后大量的重载方法,用“穷举法”把BigDecimal、Double、String、Integer四种类型进行各种形式的两两组合,进行加减乘除运算。运算时非BigDecimal类型的参数会转化成BigDecim......
  • Survey on Reasoning Capabilities and Accessibility of Large Language Models Usin
    本文是LLM系列文章,针对《SurveyonReasoningCapabilitiesandAccessibilityofLargeLanguageModelsUsingBiology-relatedQuestions》的翻译。使用生物学相关问题对大型语言模型的推理能力和可访问性的调查摘要1引言2相关工作3方法4结果5讨论结论......
  • java 第10天 String创建以及各类常用方法
    一.String创建的两种形式1.通过new的当时Stringstr=newString();2.不new的方式 Strings1="";二.new和不new的方式的区别是什么不new创建的字符串首先是拿着值去常量池中查找,是否有该内容,有就用常量池该字符串的地址,没有的话在常量池中创建并使用new的方式创建的字......
  • 【MySQL】[HY000][1366] Incorrect string value: ‘\xE4\xB8\xA4\xE6\x95\xB0.
    问题描述在导入中文数据时遇到错误。[2024-10-1610:49:49][HY000][1366]Incorrectstringvalue:'\xE4\xB8\xA4\xE6\x95\xB0...'forcolumn'title'atrow1尝试将某些数据插入到名为’title’的列时,遇到了不正确的字符串值。原因分析MySQL5.7创建数据库的默......
  • c#声明枚举,通过枚举int获取枚举value、通过枚举value获取int值、判断string值是否存在
    c#声明枚举,通过枚举int获取枚举value、通过枚举value获取int值、判断string值是否存在枚举中 1、声明枚举每个枚举常量可以用一个标识符来表示,也可以为它们指定一个整数值,如果没有指定,那么默认从 0 开始递增。注意:第一个枚举成员的默认值为整型的0,后续枚举成员的值在前......
  • ERROR require() of ES Module ...\node_modules\string-width\index.js from ...
    nuxt3安装jq的依赖,其实不止jq,只要是安装个新的依赖就报错:ERRORrequire()ofESModule...\node_modules\string-width\index.jsfrom...\node_modules\wide-align\align.jsnotsupported.解决方案:删掉yarn.lock和node_modules重新安装则没问题,然后在github和gi......
  • Incorrect string value: ‘\xE8\x8D\x98\xE8\x83\xBD...‘ for column
    mysql>SELECTVERSION();+------------+|VERSION()|+------------+|5.6.51-log|+------------+1rowinset(0.00sec)[2024-10-1513:51:26]已连接>useproductqualification[2024-10-1513:51:26]在3ms内完成productqualification>INSERTINTO`......