Search code examples
c#templatesconsole.writeline

C# WriteLine method shows numbers inside brackets instead of what I want the to be replaced with


I just started learning C# and this is my code of a simple program for homework:

using System;

namespace Concatenate_Data
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = Console.ReadLine();
            string lastName = Console.ReadLine();
            int age = int.Parse(Console.ReadLine());
            string town = Console.ReadLine();

            Console.WriteLine($"You are {0} {1}, a {2}-years old person from {3}.", firstName, lastName, age, town);
        }
    }
}

Instead of outputting for instance "You are Peter Johnson, a 20-years old person from Sofia.", it outputs "You are 0 1, a 2-years old person from 3. How can I fix this? I even copied the code 1:1 from the sample they gave us.


Solution

  • $ sign makes the string as an interpolated string. So it doesn't work as string.Format() works. You may refer documentation here

    You may get the desired output when you write the code as per the following;

    Console.WriteLine($"You are {firstName} {lastName}, a {age}-years old person from {town}.");