What is the optional argument in C# interpolated string for?

北城余情 提交于 2019-11-30 00:15:48

问题


Interpolated strings is one of the new features of C# 6.0.

According to MSDN, the syntax of the embedded C# expressions can contain an optional, comma-separated value, deemed as <optional-comma-field-width> in the documentation.

Unfortunately I didn't find what this field is for.

From its name one might think that this value sets the maximal size of the "interpolated" field, but when I try the following expression:

var p = Process.GetCurrentProcess();
Console.WriteLine($"Process name is {p.ProcessName, 5}");

I get the following output:

Process name is LINQPad.UserQuery

回答1:


It's the minimum width to use for that field, not the maximum. Since your string is longer than the 5 characters you specify for the width, the field is extended to the length of your string. You'll see the difference more dramatically with a longer width:

var p = Process.GetCurrentProcess();
$"Process name is {p.ProcessName, 50}".Dump();

yields:

Process name is                                  LINQPad.UserQuery

A positive field size is right-justified; a negative field size is left-justified.

The documentation is better on the Composite Formatting page of MSDN:

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.




回答2:


The number is the alignment, documented in the Alignment Component here.

The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative.

In your example, alignment will pad the p.ProcessName with spaces if it is less than 5 characters long. Where string length is less than the absolute value of alignment (like in your example), alignment has no effect.

Example

var text = "MyText";
Console.WriteLine($"x{text}x");
Console.WriteLine($"x{text, 3}x");
Console.WriteLine($"x{text, 10}x");
Console.WriteLine($"x{text, -10}x");

Result

xMyTextx
xMyTextx
x    MyTextx
xMyText    x


来源:https://stackoverflow.com/questions/32620851/what-is-the-optional-argument-in-c-sharp-interpolated-string-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!