C# Basic Console Input and Output
Objectives
- What is Basic Console Input and Output?
- Console.WriteLine()
- Console.ReadLine()
- Formatting output
What is Basic Console Input and Output?
Console I/O in C# is the term used to describe how we interact with the console window through standard input/output operations. It allows us to give information to the user and take in data from the user via the console.
Console.WriteLine().
The method is used for displaying output on to the console window.
This method prints out displayed text followed by a line break so that it moves cursor down to next line.
Example:
Console.WriteLine("Hello, World!");
Console.ReadLine():
The purpose of this method is to read input from console window.
It reads a line of characters from its default input stream (console) and returns it as a string.
Example:
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
Formatting Output:
You may format output using composite formatting, string interpolation, or formatting placeholders.
Composite Formatting:
string name = "John";
int age = 30;
Console.WriteLine("Name: {0}, Age: {1}", name, age);
String Interpolation:
string name = "John";
int age = 30;
Console.WriteLine($"Name: {name}, Age: {age}");
Formatting Placeholders:
string name = "John";
int age = 30;
Console.WriteLine("Name: {0,-10} | Age: {1,3}", name, age);
In this example above, {0,-10} implies that name will be left aligned within 10 character wide column whereas {1,3} means age will be right aligned in 3 character wide column.