C#: Reading input using Readline()

This entry is part 11 of 71 in the series C#

We have used WriteLine() to output a string of characters.

If you have learnt C before, some of the earlier programs that you have written could be related to reading a text input from the console.

To read input from user, we could use ReadLine().  The program below will prompt the user to input his name.

using System;

namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            string name;

            Console.WriteLine("Hello, what is your name?");
            name=Console.ReadLine();
            Console.WriteLine("Your name is " + name);
            Console.ReadLine();
        }
    }
}

ReadLine() is similar to WriteLine().  It is a method under the Console class.

The output of the program will be similar to the screenshot below.

input

Notice that when we run the program, we are actually not passing any argument in the command line when typing ConsoleHelloApplication.exe.

commandline

So we could further simplify the program on line 7 to:

using System;

namespace Hello
{
    class Program
    {
        static void Main()
        {
            string name;

            Console.WriteLine("Hello, what is your name?");
            name=Console.ReadLine();
            Console.WriteLine("Your name is " + name);
            Console.ReadLine();
        }
    }
}

readline

Series Navigation<< C#: namespace and class
C#: The Main function >>

Leave a comment

Leave a Reply