System.Console Class
Namespace: System
Provides access to the standard input, output, and error streams for console applications. This class cannot be inherited.
Syntax
public static class Console
Remarks
The Console class provides methods for interacting with the console, such as reading input from the keyboard, writing output to the screen, and manipulating the console's appearance. It is a fundamental class for building command-line applications in .NET.
Key features include:
- Reading text and numeric input.
- Writing text and formatted output.
- Controlling cursor position and console colors.
- Handling key presses.
Note: The behavior of the
Console class may vary slightly depending on the operating system and the environment in which the application is run.
Methods
| Member | Type | Description |
|---|---|---|
ReadLine |
string ReadLine() |
Reads the next line of characters from the standard input stream and returns it as a string. |
WriteLine |
void WriteLine(string value) |
Writes the specified string value, followed by the current line terminator, to the standard output stream. |
ReadKey |
ConsoleKeyInfo ReadKey() |
Reads the next key pressed by the user and returns information about the key. |
Clear |
void Clear() |
Clears the console buffer and the corresponding display memory. |
Beep |
void Beep() |
Emits a standard beep sound through the console speaker. |
Properties
| Member | Type | Description |
|---|---|---|
InputEncoding |
Encoding InputEncoding { get; set; } |
Gets or sets the Encoding for the standard input stream. |
OutputEncoding |
Encoding OutputEncoding { get; set; } |
Gets or sets the Encoding for the standard output stream. |
ForegroundColor |
ConsoleColor ForegroundColor { get; set; } |
Gets or sets the current foreground color of the console text. |
BackgroundColor |
ConsoleColor BackgroundColor { get; set; } |
Gets or sets the current background color of the console text. |
Example Usage
The following C# code snippet demonstrates how to use the Console class to get user input and display output:
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to the .NET Console Application!");
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Hello, {name}! Welcome aboard.");
Console.ResetColor(); // Reset to default colors
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
Tip: Remember to call
Console.ResetColor() after setting custom colors to avoid affecting subsequent output.