C # Interpolation with Variable Format Strings

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[] args) { int i = 12345; Console.WriteLine($"Test 1: {i:N5}"); var formatString = "N5"; Console.WriteLine($"Test 2: {i:formatString}"); } 

Test 1 works, test 2 does not work.

What is the exact syntax for test 2?

+5
source share
5 answers

Your code is equivalent to:

 Console.WriteLine(String.Format("Test 2: {0:formatString}", i)); 

Since formatString is in the format string, you can String.Format calls to put the value in the format string:

 Console.WriteLine(String.Format(String.Format("Test 2: {{0:{0}}}", formatstring), i)); 

This is not supported by string interpolation.

+3
source

C # has no syntax that will do what you want.

+2
source

The shortest way to do this is "syntactically" without String.Format, using ToString :

 $"Test 2: {i.ToString(formatString)}" 
+1
source

String interpolation occurs at the compilation stage. Because of this, you cannot use variables in format strings.

0
source

I 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(); } 
0
source

All Articles