Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the string formatter be parametrized with variables?

Example

Here is an example:

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Test {0, 10}", 1100);
        Console.WriteLine("Test {0, 10}", 2);
        Console.WriteLine("Test {0, 10}", 40);
    }
}

The output is:

Test       1100
Test          2
Test         40
Press any key to continue . . .

Question

Is it possible to make the number 10 in the above example variable?

The following depicts the intention, but does not compile because a string is expected, not an int:

public class Program
{
    public static void Main(string[] args)
    {
        int i = 10;
        Console.WriteLine("Test {0, i}", 1100);
        Console.WriteLine("Test {0, i}", 2);
        Console.WriteLine("Test {0, i}", 40);
    }
}
like image 431
Lernkurve Avatar asked Jan 07 '23 11:01

Lernkurve


1 Answers

With C# 6 you can use string interpolation:

Console.WriteLine($"Test {{0, {i}}}", 1100);
Console.WriteLine($"Test {{0, {i}}}", 2);
Console.WriteLine($"Test {{0, {i}}}", 40);

The benefit of string interpolation in C# 6 is that it includes compile-time checking of variables. In order to make string interpolation work you need to prefix your string with a dollar sign ($).

Another option without string interpolation would be this:

int i = 10;
Console.WriteLine("Test {0, " + i + "}", 1100);
Console.WriteLine("Test {0, " + i + "}", 2);
Console.WriteLine("Test {0, " + i + "}", 40);

Or:

Console.WriteLine("Test " + 1100.ToString().PadLeft(i));
Console.WriteLine("Test " + 2.ToString().PadLeft(i));
Console.WriteLine("Test " + 40.ToString().PadLeft(i));
like image 75
Patrick Hofman Avatar answered Jan 22 '23 19:01

Patrick Hofman