2

In C#7, (.NET Framework 4.7+), what is the proper way to include a variable in the alignment component for string interpolation?

The following code gives an error "constant value is expected" for the alignment component.

var x = 5;
var test = $"{"blue",x}";

The C# specs for string interpolation alignment element read:

{<interpolatedExpression>[,<alignment>][:<formatString>]}

alignment

The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression....

Is there a workaround for the "constant expression" limitation of the alignment setting? Could this be performed with other built-in functions?

Also curious as to why it was implemented with this limitation.

Eugene
  • 10,957
  • 20
  • 69
  • 97
  • 3
    If you want the alignment to be defined at runtime, you can use `string.Format` – vc 74 Mar 23 '19 at 05:18
  • 1
    @vc74 Looking at [string composite formatting](https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting) it seems string.Format is the alternative, though it's not as clean as $ string interpolation. Was hoping there was a workaround of sorts. – Eugene Mar 23 '19 at 05:23
  • 1
    Keep in mind that `FormattableString` instances are transformed at compile time so the compiler needs to know the actual value of the alignment. – vc 74 Mar 23 '19 at 05:35
  • 1
    Interpolated strings aren't magic. They are just syntactic sugar for calling `string.Format()`. They simply allow you to reorganize the string so that instead of explicitly providing argument indexes, and then a list of arguments, the compiler does that for you. The usual limitations with `string.Format()` still apply, including the requirement that alignment values be integer literals in the format string. But, you can generate the format string at run-time as a work-around. See marked duplicate for details. – Peter Duniho Mar 23 '19 at 05:39
  • And don't forget: you can use interpolated strings to create the string format! E.g.: `string test = string.Format($"{{0,{x}}}", "blue");` String interpolation happens at compile-time, so you're stuck calling `string.Format()` explicitly, but interpolation at least lets you create the format string a bit more conveniently. – Peter Duniho Mar 23 '19 at 06:01

0 Answers0