Displaying Output To The Console
Lesson 5.2: Displaying Output to the Console
In this lesson, you'll learn how to present information and messages to the user through the console window. This is a fundamental skill for providing feedback, displaying results, and creating interactive programs.
The Console.WriteLine() Method
You've already seen Console.WriteLine() in action! It's the most common way to display text output in the console.
This method prints the text you provide as an argument, followed by a new line character (which moves the cursor to the beginning of the next line).
Example: Simple Output
C#
Console.WriteLine("Hello, World!");
Console.WriteLine("This is another line of text.");
Output:
Hello, World!
This is another line of text.
Formatting Output
You can include placeholders within the text string to insert variable values or format numbers.
Placeholders are denoted by curly braces {} followed by a number indicating the index of the argument to insert.
C#
string name = "Alice";
int age = 30;
double price = 19.99;
Console.WriteLine("Name: {0}, Age: {1}", name, age);
Console.WriteLine("The price is {0:C}", price); // C for currency format
Output:
Name: Alice, Age: 30
The price is $19.99
Other Console Methods
Console.Write(): Prints text without adding a new line at the end.
Console.ForegroundColor: Changes the color of the text in the console.
Console.BackgroundColor: Changes the background color of the text in the console.
Console.Clear(): Clears the console window.
Example: Formatted and Colored Output
C#
Console.ForegroundColor = ConsoleColor.Green; // Set text color to green
Console.WriteLine("This is green text.");
Console.BackgroundColor = ConsoleColor.Yellow; // Set background color to yellow
Console.WriteLine("This is yellow background.");
Console.ResetColor(); // Reset colors to defaults
Console.Write("Back to normal. ");
Console.Write("This is on the same line.");
Advanced Formatting (Optional)
For more precise control over output formatting, you can use string interpolation or the string.Format() method. These techniques allow you to embed expressions directly within string literals.
Example: String Interpolation
C#
string city = "New York";
int population = 8_336_817; // Underscores for readability
Console.WriteLine($"The population of {city} is {population:N0}."); // N0 for number format with commas
Output:
The population of New York is 8,336,817.
Key Points
Console.WriteLine(): Prints text followed by a new line.
Console.Write(): Prints text without a new line.
Formatting placeholders: {} followed by an index.
String interpolation: Embed expressions directly in strings using $.
Let me know if you have any other questions.