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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With