官术网_书友最值得收藏!

String interpolation

String interpolation is a more elegant and easier-to-work-with version of the familiar string format method. Instead of supplying the arguments to embed in the string placeholders separately, you can now embed them directly in the string. This is far more readable and less error-prone.

Let's demonstrate this with an example. Consider the following code that embeds an exception in a string:

catch (Exception e)
{
Console.WriteLine("Oh dear, oh dear! {0}", e);
}

This embeds the first (and in this case only) object in the string at the position marked by zero. It may seem simple, but it quickly gets complex if you have many objects and want to add another at the start. You then have to correctly renumber all the placeholders.

Instead, you can now prefix the string with a dollar character and embed the object directly in it. This is shown in the following code that behaves the same as the previous example:

catch (Exception e)
{
Console.WriteLine($"Oh dear, oh dear! {e}");
}

The ToString() method on an exception outputs all the required information, including the name, message, stack trace, and any inner exceptions. There is no need to deconstruct it manually; you may even miss things if you do.

You can also use the same format strings as you are used to. Consider the following code that formats a date in a custom manner:

Console.WriteLine($"Starting at: {DateTimeOffset.UtcNow:yyyy/MM/dd HH:mm:ss}");

When this feature was being built, the syntax was slightly different. So, be wary of any old blog posts or documentation that may not be correct.

主站蜘蛛池模板: 阿鲁科尔沁旗| 红安县| 云和县| 清涧县| 略阳县| 墨玉县| 千阳县| 万山特区| 稻城县| 夹江县| 营山县| 新郑市| 满洲里市| 廊坊市| 泸水县| 和龙市| 贵溪市| 阿拉善盟| 会泽县| 德州市| 河北区| 徐闻县| 哈尔滨市| 台南市| 开平市| 宜川县| 双辽市| 怀化市| 鸡泽县| 洮南市| 巧家县| 肃宁县| 宁武县| 肥西县| 海城市| 徐州市| 遂昌县| 江阴市| 灵寿县| 沙湾县| 锡林浩特市|