+ 8
why is there a {0} after the "hello" in output
3 Answers
+ 23
string yourName;
Console.WriteLine("What is your name?");
yourName = Console.ReadLine();
Console.WriteLine("Hello {0}", yourName);
I think you meant this ^^
In the input ("Hello {0}", yourName), {0} represents yourName. If you gone through all the lessons, you would have known that C# counts from 0 and the input inside the Console.WriteLine are actually elements, hence yourName is element number 1.
But heres the tricky part, since {0} is inside the string of text with Hello, the counting will then begin from the next element. Hence the next element will begin from 0 in the "Hello {0}" perspective. BUT "Hello {0}" is still element number 0 in Console.WriteLine's perspective.
[Pretty confusing and hard to understand isn't it?]
^^ based on that, there is alternative way to rewrite that.
Instead of
Console.WriteLine("Hello {0}", yourName);
Heres the 2nd way :
Console.WriteLine("Hello " + yourName);
Remember the additional space after hello, the system wont automatically add spaces for you.
+ 15
Think of {0}, {1}, etc as placeholders for values. Consider the line of code
Console.WriteLine( "I had breakfast with {0} and he eat {2} pieces of {3}, while I went with just a {1}", "George", âcoffeeâ, 2, âpieâ, "not used", 3.14 )
It outputs "I had breakfast with George and he eat 2 pieces of pie, while I went with just a coffee.
The placeholders {0}, {1}, etc in the string to be outputed will be replaced with the values you add after the string. The 0 in {0} is the order, counting from 0 like with arrays.
You can use the placeholders in any order, and you can use them with values of any type that converts to string. Any other values that won't be used are simply ignored, in the example "not used" and 3.14
+ 1
it represents or indexes the variable list after the quotations.