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?
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?
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.
As previously mentioned alignment must be constant, but could try using Padleft in a similar fashion (not sure if that would work for you or not).
That or would have to have various string interpolations for 1 string.
string test;
if (value.length > 100)
test = "${value: -20}";
else test = "${value : 20}";
Hope this helps.
Why not pad left?
var p = Math.Max(Math.Max(a.Length, b.Length), c.Length);
Console.WriteLine(a.PadLeft(p));
Console.WriteLine(b.PadLeft(p) + " +");
Console.WriteLine(new string('-', p));
Console.WriteLine(c.PadLeft(p));
It's dynamic and (in my use case) adaptive:
© 2022 - 2024 — McMap. All rights reserved.
String.Format
. If you can't do something viaFormat
, you cannot do it via string interpolation. – Apiary