Console.ReadLine and Console.WriteLine in C#

In our previous post, we looked at one of the way to get input from the user via command line arguments. But in that case you have to provide all inputs at once. We require our programs to be interactive. They should prompt for the information they require.

 



We will implement the program for the below scenario -

Computer: What is your name?
You: CheezyCode
Computer: Welcome CheezyCode.

using System;

class Program
{
    static void Main(String[] args)
    {
        Console.WriteLine("What is your name?");
        
        // read from console and store it in a variable name of type string
        string name = Console.ReadLine();
        
        Console.WriteLine("Welcome " + name);
        Console.Read();
    }
}

Console.WriteLine -  as it's name suggests - it will write a line on the console. Similarly, Console.ReadLine will read input from the console and return it as a string which can be stored in a variable. In above code snippet, input is read from the console via Console.ReadLine and stored in a name variable. Then, name variable is used in Console.WriteLine to print what has been entered by the user. You can use Console.ReadLine multiple times if you want to take multiple input from the user.

cheezycode-readline-writeline-csharp


"Welcome " + name -  will append name to the Welcome string. + is used to append 2 or more strings together. There is one more way to append strings which is more readable. You can use -  Console.WriteLine("Welcome {0}", name); Here {0}, will act as a placeholder which is replaced by the value of name variable at runtime. We will revisit String class again in future posts.

Let us know for any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)


Comments

Post a Comment

Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Android Apps - Getting Started