Search code examples
c#string-interpolation

A constant value is expected in string interpolation


My code is as follows

static string Foo(string str, int width)
{
    return $"{str,width}";
}

The compiler isn't letting me use the width variable. How can I pass this to a method?


Solution

  • In this case you might be better off to use string.Format than interpolation.

    var str = "test";
    var width = 10;
    var fmt = $"{{0,{width}}}";
    var result = string.Format(fmt, str);
    

    But if you're simply padding with spaces PadLeft or PadRight would be cleaner...

    return str.PadLeft(width, ' ');