I need to format a variable with string interpolation, and the format string is another variable:
here is my sample code:
static void Main(string[] a
You can make a simple extension method that allows you to call a formattable ToString
method on any object. The IFormattable
interface is the same way that string.Format
or interpolated strings would use to format an object of unknown type.
public static string ToString(this object value, string format, IFormatProvider provider = null)
=> (value as IFormattable)?.ToString(format, provider) ?? value.ToString();
And to use:
object i = 12345;
var formatString = "N5";
Console.WriteLine($"Test 2: {i.ToString(formatString)}");