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.

5
  • 3
    If you want the alignment to be defined at runtime, you can use string.Format Commented Mar 23, 2019 at 5:18
  • 1
    @vc74 Looking at string 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. Commented Mar 23, 2019 at 5: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. Commented Mar 23, 2019 at 5: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. Commented Mar 23, 2019 at 5: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. Commented Mar 23, 2019 at 6:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.