Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how do you use placeholders in Console.WriteLine()? [duplicate]

Tags:

c#

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();
like image 731
shampouya Avatar asked Dec 08 '22 03:12

shampouya


2 Answers

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.

like image 70
Jeroen Vannevel Avatar answered May 20 '23 09:05

Jeroen Vannevel


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); 
like image 33
Rahul Avatar answered May 20 '23 11:05

Rahul