Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
PBG Avatar asked Oct 18 '25 15:10

PBG


1 Answers

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, ' ');
like image 160
dazedandconfused Avatar answered Oct 20 '25 05:10

dazedandconfused