Console I/O
Explore how to manage console input and output in C# by using methods like Console.WriteLine, string interpolation, and tab or newline characters. Learn to read input safely with Console.ReadLine and handle type conversions with TryParse to prevent errors from invalid input.
We have already written several statements that print to the console. This lesson provides examples to consolidate that knowledge.
Console output
Two primary methods handle console output:
The
Console.Write()method prints to the console and keeps the cursor on the same line.The
Console.WriteLine()method prints to the console and moves the cursor to the next line.
Let’s review the following code snippets to see the difference.
Lines 3–4: We call
Console.Writetwice. Because this method does not append a new line character, “World” is printed immediately after “Hello” on the same line.
To make these statements print on separate lines, we can use the Console.WriteLine() method.
Line 3: Prints “Hello” and moves the cursor to the start of the next line.
Line 4: Prints “World” on the new line.
Now, "Hello" and "World" appear on separate lines. However, using the WriteLine() method isn’t the only way we can insert line endings.
Using \n for line breaks
We can use the special \n character for carriage returns. This character ...