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 . . .
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);
}
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With