jaguar68
jaguar68

Reputation: 179

C# string interpolation with variable format

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 don't work.

What's the exact syntax for Test 2 ?

Upvotes: 12

Views: 16490

Answers (6)

Rhaokiel
Rhaokiel

Reputation: 843

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)}");

Upvotes: -1

Aldracor
Aldracor

Reputation: 2181

The shortest way you can do this 'syntactically' without String.Format, is using ToString:

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

Upvotes: 11

Guffa
Guffa

Reputation: 700212

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.

Upvotes: 7

Marnix
Marnix

Reputation: 6547

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

Upvotes: 1

SLaks
SLaks

Reputation: 887285

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

Upvotes: 1

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31143

The string interpolation happens in the compilation stage. You cannot use variables in the format strings because of that.

Upvotes: 0

Related Questions