In this article [Show more]
What is Console in C#?
In C#, the Console class, part of the System namespace, provides essential functionality for interacting with the command-line interface. It is often used to develop command-line applications and to facilitate debugging and logging in graphical applications. This article explains what Console is, its key features, and how to use it effectively in C# programs.
Key Features of the Console Class
Input and Output
The Console class provides methods to read input from the user and write output to the screen.
- Input: Read and ReadLine methods receive user input.
- Output: Write and WriteLine methods print messages to the console.
Text Formatting
- Colors: Change the text color with ForegroundColor and background color with BackgroundColor.
- Cursor: Adjust the cursor position for precise text placement.
Stream Redirection
- Input/Output Streams: Redirect the input or output streams to read from/write to files or other sources.
Practical Examples of Console Operations
Input and Output Example
using System;
public class ConsoleInputOutputExample
{
public static void Main()
{
// Prompt the user for their name
Console.Write("Enter your name: ");
string name = Console.ReadLine();
// Greet the user
Console.WriteLine($"Hello, {name}!");
// Prompt the user for their age
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
// Display the entered age
Console.WriteLine($"You are {age} years old.");
}
}
Changing Text Colors
using System;
public class ConsoleColorsExample
{
public static void Main()
{
// Set text color to Green
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("This is green text!");
// Set background color to Blue and text color to Yellow
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Yellow text on a blue background!");
// Reset colors to default
Console.ResetColor();
Console.WriteLine("Default colors restored.");
}
}
Redirecting Input and Output Streams
using System;
using System.IO;
public class ConsoleRedirectExample
{
public static void Main()
{
// Redirect the output stream to a file
using (StreamWriter writer = new StreamWriter("output.txt"))
{
Console.SetOut(writer);
Console.WriteLine("This text is written to output.txt instead of the console.");
}
// Restore the original console output
Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
}
}
Conclusion
The Console class in C# is a versatile tool for reading user input, writing formatted output, and manipulating text styles. By leveraging its key features, you can build interactive applications and perform efficient logging or debugging.