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
Your code is equivalent to:
Console.WriteLine(String.Format("Test 2: {0:formatString}", i));
As the formatString
is in the format string, you would nest String.Format
calls to put the value in the format string:
Console.WriteLine(String.Format(String.Format("Test 2: {{0:{0}}}", formatstring), i));
This isn't supported with string interpolation.
C# has no syntax that will do what you want.
The string interpolation happens in the compilation stage. You cannot use variables in the format strings because of that.
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)}");
I have tested this piece of code and it seems to work:
static void Main(string[] args)
{
int i = 12345;
Console.WriteLine("Test 1: {0:N5}",i);
var formatString = "N5";
Console.WriteLine("Test 2: {0:" + formatString + "}", i);
Console.ReadLine();
}
The shortest way you can do this 'syntactically' without String.Format, is using ToString
:
$"Test 2: {i.ToString(formatString)}"