Christian Gallo Christian Gallo - 19 days ago 6
C# Question

How do you redirect input as out put with ReadLine and WriteLine? (Noob)

i am trying to create a small game but i want the user to input his name so the game is a bit more realistic! how????
i am trying to make it so if you enter 3 (case 3) the application just closes!
This is the code!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Game
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Does anyone copy?");
// Thread.Sleep(3000);
Console.WriteLine("Is there anybody listening?");
// Thread.Sleep(3000);
Console.WriteLine("Please i need help!!!");
//Thread.Sleep(3000);
Console.WriteLine("1. Who is this?");
Console.WriteLine("2. Yes i copy!");
Console.WriteLine("3. Ignore the message!");
String choice = Console.ReadLine();
switch (choice)
{
case "1":
//Thread.Sleep(2000);
Console.WriteLine("I'm Emma!");
//Thread.Sleep(6000);
Console.WriteLine("Oh my God i tought nobody was going to answer!");
//Thread.Sleep(2000);
Console.WriteLine("Who are you?");
break;
case "2":
//Thread.Sleep(6000);
Console.WriteLine("Oh my God i tought nobody was going to answer!");
//Thread.Sleep(2000);
Console.WriteLine("I'm Emma by the way!");
//Thread.Sleep(2000);
Console.WriteLine("Who are you?");
break;
case "3":

break;
}

Console.ReadLine();
string yourName;
yourName = Console.ReadLine();
//Thread.Sleep(10000);
Console.WriteLine("Hey {0}... Sorry i got you so worried... i was just scared someone was in my room!" yourName );
//Thread.Sleep(20000);



}
}


}

Answer

In your code you are trying to use string.Format, the correct syntax would be:

string yourName;
yourName = Console.ReadLine();
//Thread.Sleep(10000);
Console.WriteLine(String.Format("Hey {0}... Sorry i got you so worried... i was just scared someone was in my room!", yourName));
//Thread.Sleep(20000);

The important part you are missing is this Console.WriteLine(String.Format(

You also need to separate your variable and the text with a comma, as they are different parameters in the String.Format() method.

Aside from this you could also use string interpolation like so

Console.WriteLine($"Hey {yourName}... Sorry i got you so worried... i was just scared someone was in my room!");

This works similarly to String.Format, but it is instead used by adding a $ before the string.

A bonus of this is, as you can see, the variable name is inside the curly brackets - {yourName} as opposed to putting a 0. which is less code to write than in String.Format