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.
string.FormatFormattableStringinstances are transformed at compile time so the compiler needs to know the actual value of the alignment.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 withstring.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.string test = string.Format($"{{0,{x}}}", "blue");String interpolation happens at compile-time, so you're stuck callingstring.Format()explicitly, but interpolation at least lets you create the format string a bit more conveniently.