Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't C# interpolated strings accept variable padding?

Tags:

c#

C# interpolated strings allow one to add left or right padding to strings. Depending on what you're outputting, you might need to adjust the level of padding. Why does C# have a problem with using a variable to denote the padding? (Please see example below.)

public static void example(string name, ApplicationCall NxRequest)
{
    // Both 'headers' and 'values' are string arrays.
    var headers = NxRequest.Headers();
    var values = NxRequest.Values();

    // I want to set the level of padding based on the maximum length 
    // in the 'headers' string array.
    var padding = headers.Select(x => x.Length).Max();
    const int constPadding = headers.Select(x => x.Length).Max();

    for (int i = 0; i < headers.Length; i++)
    {
        // This works.
        Console.WriteLine($"{headers[i].ToUpper().PadRight(padding)} {values[i]}");

        // This doesn't work because constPadding cannot be set as a constant.
        Console.WriteLine($"{headers[i].ToUpper(), constPadding} {values[i]}");
    }
}

Edit: I introduced a better example.

like image 213
N4v Avatar asked Apr 14 '26 05:04

N4v


1 Answers

You need to make pad a constant:

foreach (var item in new string[] { "cat", "dog", "mouse" })
{
    const int pad = -12;
    Console.WriteLine($"{item, pad}");
}

If a constant cannot be used, then you must use a string padding function, such as PadLeft, or PadRight.

like image 185
Michael G Avatar answered Apr 15 '26 20:04

Michael G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!