Is it possible to parameterize string formatting using 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);
    }
}

Output:

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

Question

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

The intention is shown below, but does not compile, because it is expected string, not 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);
    }
}
+4
source share
2 answers

With C # 6, you can use the interpolation string :

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

The advantage of string interpolation in C # 6 is that it includes checking compile-time variables. To perform string interpolation, you must prefix your string with a dollar sign ( $).

:

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

:

Console.WriteLine("Test " + 1100.ToString().PadLeft(i));
Console.WriteLine("Test " + 2.ToString().PadLeft(i));
Console.WriteLine("Test " + 40.ToString().PadLeft(i));
+6

:

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);
    }
}
+3

Source: https://habr.com/ru/post/1609472/


All Articles