Search code examples
c#console-applicationconsole.readline

C#. Console.ReadLine() for two different obejcts


I'm learning C# and very new to this topic. Currently, I'm working on a small console app (just doing tasks to strengthen my knowledge) Battleship game. I want to assign two names: Player 1 and Player 2.

Question is: Can I use one reader instead of two, to assign different names? I tried to use one reader, but it assigned one name to both players.

Here is my code:

public void StartGame(Game game)
        {
            if (game.GameStage == GameStage.Start)
            {
                Console.WriteLine("Welcome to Battleship 2020.");
                Console.WriteLine("Player 1 enter your name:");

                var reader1 = Console.ReadLine();
                Player player1 = new Player();
                player1.Name = reader1;

                Console.WriteLine($"Welcome {player1.Name}");

                Console.WriteLine("Player 2 enter your name:");
                Player player2 = new Player();
                var reader2 = Console.ReadLine();
                player2.Name = reader2;

                Console.WriteLine($"Welcome {player2.Name}");
            }
        }

Solution

  • Console.ReadLine() does not return any "reader". It just returns String object which contains text grabbed from console input.
    The line in method name means it will read everything available on the input until it will encounter line break.
    If there is no line break, it will wait forever until user will press "enter" key. If there are many text lines in the bufffer, you need to call ReadLine() many times.

    You can assign player name diretly using:

     player1.Name = Console.ReadLine();