Input and Output
Input:
In C#, you can use the Console.ReadLine() method to get user input. Let’s explore how to do that:
Getting a String Input:
To read a line of text from the user, use Console.ReadLine(). It returns the input as a string.
Example
Console.WriteLine("Enter your name:");
//Type your name and press enter
string nameInput = Console.ReadLine();
Console.WriteLine("Hello, " + nameInput + "!"); // Prints the user's name
Getting Numeric Input:
If you need to obtain a numeric input, such as an integer, you must convert the string input to the desired data type.
Example
Console.WriteLine("Enter your age:");
//Type your age and press enter
string ageInput = Console.ReadLine();
int age = Convert.ToInt32(ageInput); // Convert the string to an integer
Console.WriteLine("Your age is: " + age);
Output:
There are two primary methods for displaying text and results in the console:
1. Console.WriteLine()
This method prints text followed by a newline character (moves to the next line).
Example
Console.WriteLine("Hello World!");
Result
Hello World!
2. Console.Write()
Similar to WriteLine() but without inserting a new line at the end of the output.
Example
Console.Write("Hello Estudy247! ");
Console.Write("I would like to print the text on the same line.");
Result
Hello Estudy247! I would like to print the text on the same line.
Difference Between WriteLine() and Write()
The main difference between these methods is that:
- WriteLine() prints the string provided and moves to the start of the next line.
- Write() only prints the string without adding a newline.
You may download the source code from the course repository on GitHub – https://github.com/estudy-247/input-output
