Variable alignment component in string interpolation
Asked Answered
W

3

7

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?

Wantage answered 25/7, 2018 at 17:28 Comment(1)
string interpolation is just dressed up/hidden String.Format. If you can't do something via Format, you cannot do it via string interpolation.Apiary
A
4

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.

Anglofrench answered 25/7, 2018 at 17:49 Comment(1)
This seems weird. If result string can be composed from dynamic variables, why they need constant expression for alignment? The output need to be evaluated at runtime anyway, right?Headstock
P
2

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.

Pyosis answered 25/7, 2018 at 18:1 Comment(0)
M
2

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:

enter image description here

Mimi answered 20/2 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.