Search code examples
c#stringstring-interpolation

Variable alignment component in string interpolation


The alignment component is the -20 in this example:

$"{value, -20}"

Is there a way to make an interpolated string like this:

$"{value, alignment}"

where alignment is a variable?


Solution

  • Unfortunately, alignment cannot be a variable. The alignment has to be a constant expression. Here is the relevant section from the docs

    alignment: The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned. For more information, see Alignment Component.