Home » Blog » C# – User Inputs & Outputs – Part 2

C# – User Inputs & Outputs – Part 2

InputsandOutputs

In this article, we would be having a look at user inputs and outputs in C#

User Inputs

In a console application, we take user input using Console.ReadLine().

Let’s see it in action.

//This line will print the message to the console.
Console.WriteLine("Please enter your first name:");

/*This line of code reads the user input and stores it in a variable named as firstName.*/
var firstName = Console.ReadLine();

/*This line of code emits the value of the variable firstName, along with some text.*/
Console.WriteLine("The first name which you have entered is: {0}", firstName);

Output:

Please enter your first name:
Anurag
The first name which you have entered is: Anurag

Please note that the user input is always read as string via Console.ReadLine(), hence we need a string variable to store it.

We will need to parse the strings as integers, floats, decimals etc accordingly if the user inputs are numbers.

Let’s see it in action as well.

Console.WriteLine("Please enter your age");
//The below line of code is not correct, it's a compilation error in C# 10.0.
int age = Console.ReadLine();

Let us see the correct approach to get numbers as user input and store them for further usage.

Console.WriteLine("Please enter your age");

//We convert the incoming string to integer and use it.
int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Your age is: {0}", age);

Output:

Please enter your age
30
Your age is: 30

C# Output

We have been using the C# output method for console application till now.

It is Console.WriteLine() itself. Let’s deep dive into it.

Console.WriteLine() is used to output/write onto the console. 

It adds a new line after every output.

Let’s see it in action.

Console.WriteLine("***********************************************");
Console.WriteLine("My name is John");
Console.WriteLine("My age is {0}", 32);
Console.WriteLine(10 + 10);
Console.WriteLine(20 - 10);
Console.WriteLine(20 * 10);
Console.WriteLine(20 / 10);
Console.WriteLine("Today's date is:{0}", DateTime.Now.ToShortDateString());

Output:

***********************************************
My name is John
My age is 32
20
10
200
2
Today's date is:16-06-2022

C# also has a Console.Write() method which also outputs to the console but doesn’t add a new line.

Console.Write("Hello World!");
Console.Write("It's a great day!!!");

Output:

Hello World!It's a great day!!!

Console.WriteLine() is used most of the times as compared to Console.Write()

We can equate it to console.log() method of JavaScript.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *