Code inspection: Use format specifier in interpolated strings
This inspection suggests using the full capabilities of string interpolation in C#, including specifying the format and controlling the field width.
In the example below, the original interpolated string includes explicit calls of ToString() and PadLeft(), which could be replaced by the colon : and comma , notations respectively.
public void Test(int i)
{
var str = $"Result: { i.ToString("format").PadLeft(3) }";
}
public void Test(int i)
{
var str = $"Result: { i,3:format }";
}
In the suggested fix:
3following the comma,is specifying a fixed width for the conversion. In this context, it will make sure that the string representation ofiis at least 3 characters wide.formatfollowing the colon:is a placeholder for the specific formatting you want to use.
06 June 2024