Am I using the {0}
and {1}
correctly in the code below for the name variable and age variable? What are the {0}
and {1}
called, are they formally called "placeholders"? Is it more preferable to use the + concatenation or the placeholder system to incorporate variables into Console.Writeline()
?
Console.WriteLine("Hi " + nameInput + ", you are " + ageInteger + " years old.");
Console.WriteLine("Hi {0}, you are {1} years old.", nameInput, ageInteger);
full code:
string nameInput;
string ageInputString;
int ageInteger;
Console.WriteLine("Enter your name");
nameInput = Console.ReadLine();
Console.WriteLine("Enter your age");
ageInputString = Console.ReadLine();
Int32.TryParse(ageInputString, out ageInteger);
Console.WriteLine("Hi " + nameInput + ", you are " + ageInteger + " years old.");
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
With C# 6, you can now use the hybrid solution:
Console.WriteLine($"Hi {nameInput} you are {ageInteger} years old.");
This is referred to as string interpolation.
Yes they are called placeholders. Again, doesn't it look more readable when you say like below instead of concatenation
Console.WriteLine("Hi {0} you are {1} years old.", nameInput, ageInteger);
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