4

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();
Waqar
  • 8,558
  • 4
  • 35
  • 43
shampouya
  • 386
  • 1
  • 6
  • 24

3 Answers3

11

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.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • According to [the documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated), this approach should be preferred because: _String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature_. – Lucas Aug 21 '19 at 17:00
  • Also something to keep in mind is [Always use placeholders and avoid string interpolation](https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/) – malat Oct 20 '21 at 08:30
3

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); 
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

{0} and {1} are called placeholders or format items.

As for the second question check String output: format or concat in C#?

Community
  • 1
  • 1
kyrylomyr
  • 12,192
  • 8
  • 52
  • 79