Search code examples
stringreadlineconsole.writeline

How do I add +string within a text?


I would like to know how to add [+line] within a Console.WriteLine / Console.Write.

For example:

string line;
    Console.WriteLine("Enter one or more lines of text (press 'gg' to exit):");
    do
    {
       Console.Write(" ");
        line = Console.ReadLine();
        if (line != "b")
            Console.WriteLine(" Sorry, you wrote **???**, which is wrong. \n Try again." +line);
       else
           Console.WriteLine("u rock");
    }
           while ( line != "gg") ;

I want to add [+line] in the middle of the sentence, where the question marks are. How do I do that?


Solution

  • String interpolation is your best bet (assuming you're on C# 6 or above). Remember the $ at the start of the string:

    Console.WriteLine($"Sorry, you wrote {line}, which is wrong. \n Try again.");
    

    You could have also used to separate strings added together, though this is a bit more clunky:

    Console.WriteLine("Sorry, you wrote " +  line + ", which is wrong. \n Try again.");