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

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.

主站蜘蛛池模板: 南宁市| 浪卡子县| 永嘉县| 贺兰县| 上蔡县| 侯马市| 竹山县| 合水县| 南京市| 泸州市| 巴塘县| 磴口县| 绩溪县| 墨竹工卡县| 峡江县| 孝昌县| 师宗县| 丰原市| 沛县| 普兰店市| 芜湖市| 古丈县| 汶川县| 楚雄市| 宜兰县| 红桥区| 锡林浩特市| 枞阳县| 嘉鱼县| 木兰县| 河北区| 盐源县| 图们市| 青海省| 宜昌市| 巴楚县| 章丘市| 西乌| 富源县| 黎川县| 济阳县|