Skip to main content

4.1 - Working with the Console

The console is a text-based interface that allows users to interact with applications through commands and text output. In C#, the Console class provides methods for reading input from and writing output to the console window. This class is part of the System namespace and is essential for creating command-line applications.

4.1.1 - Console Input and Output

The Console class provides several methods for basic input and output operations. These methods are static, meaning you can call them directly on the Console class without creating an instance.

4.1.1.1 - Basic Output Methods

The most commonly used output methods are:

  • Console.Write(): Writes the specified data to the console without adding a new line.
  • Console.WriteLine(): Writes the specified data to the console and adds a new line.

Example:

using System;

class Program
{
static void Main()
{
// Write without a new line
Console.Write("Hello, ");

// Write with a new line
Console.WriteLine("World!");

// This will appear on a new line
Console.WriteLine("Welcome to C# programming!");
}
}

Output:

Hello, World!
Welcome to C# programming!

4.1.1.2 - Basic Input Methods

For reading input from the console, the following methods are commonly used:

  • Console.Read(): Reads the next character from the input stream and returns its ASCII value as an integer.
  • Console.ReadLine(): Reads the next line of characters from the input stream and returns it as a string.
  • Console.ReadKey(): Reads the next key pressed by the user and returns it as a ConsoleKeyInfo object.

Example:

using System;

class Program
{
static void Main()
{
// Prompt the user for input
Console.WriteLine("Please enter your name:");

// Read a line of text
string name = Console.ReadLine();

// Display a greeting
Console.WriteLine($"Hello, {name}!");

// Wait for a key press before closing
Console.WriteLine("Press any key to exit...");
ConsoleKeyInfo key = Console.ReadKey();

// Display which key was pressed
Console.WriteLine($"\nYou pressed: {key.KeyChar}");
}
}

4.1.2 - Formatting Console Output

C# provides several ways to format console output to make it more readable and presentable.

4.1.2.1 - String Formatting

You can format strings using the string.Format() method or string interpolation (using the $ prefix).

Example:

using System;

class Program
{
static void Main()
{
string name = "Alice";
int age = 30;

// Using string.Format()
string message1 = string.Format("Name: {0}, Age: {1}", name, age);
Console.WriteLine(message1);

// Using string interpolation (C# 6.0 and later)
string message2 = $"Name: {name}, Age: {age}";
Console.WriteLine(message2);

// Formatting numeric values
double price = 123.456;
Console.WriteLine($"Price: {price:C}"); // Currency format
Console.WriteLine($"Price: {price:F2}"); // Fixed-point format with 2 decimal places
Console.WriteLine($"Price: {price:P}"); // Percentage format
Console.WriteLine($"Price: {price:E}"); // Exponential format
}
}

Output:

Name: Alice, Age: 30
Name: Alice, Age: 30
Price: $123.46
Price: 123.46
Price: 12,345.60%
Price: 1.234560E+002

4.1.2.2 - Composite Formatting

The Console.WriteLine() and Console.Write() methods support composite formatting, which allows you to insert values into a formatted string.

Example:

using System;

class Program
{
static void Main()
{
int x = 10;
int y = 20;

// Using composite formatting
Console.WriteLine("The values are {0} and {1}", x, y);

// You can reuse placeholders
Console.WriteLine("Sum: {0} + {1} = {2}", x, y, x + y);

// You can specify alignment and formatting
Console.WriteLine("{0,10} {1,10}", "Name", "Age"); // Right-aligned, 10 characters wide
Console.WriteLine("{0,10} {1,10}", "Alice", 30);
Console.WriteLine("{0,10} {1,10}", "Bob", 25);
}
}

Output:

The values are 10 and 20
Sum: 10 + 20 = 30
Name Age
Alice 30
Bob 25

4.1.3 - Console Colors and Styling

The Console class allows you to change the foreground (text) and background colors to enhance the visual appearance of your console applications.

4.1.3.1 - Setting Colors

You can set the foreground and background colors using the ForegroundColor and BackgroundColor properties.

Example:

using System;

class Program
{
static void Main()
{
// Save the original colors
ConsoleColor originalForeground = Console.ForegroundColor;
ConsoleColor originalBackground = Console.BackgroundColor;

// Change colors
Console.ForegroundColor = ConsoleColor.Green;
Console.BackgroundColor = ConsoleColor.Black;

Console.WriteLine("This text is green on black background");

// Change to different colors
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Blue;

Console.WriteLine("This text is yellow on blue background");

// Reset to original colors
Console.ForegroundColor = originalForeground;
Console.BackgroundColor = originalBackground;

Console.WriteLine("This text has the original colors");
}
}

4.1.3.2 - Available Colors

The ConsoleColor enumeration provides the following color options:

using System;

class Program
{
static void Main()
{
// Display all available console colors
foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor)))
{
Console.ForegroundColor = color;
Console.WriteLine($"This text is in {color} color");
}

// Reset to default color
Console.ResetColor();
}
}

4.1.3.3 - Creating a Colorful Menu

You can use colors to create visually appealing menus in console applications:

using System;

class Program
{
static void Main()
{
bool exit = false;

while (!exit)
{
Console.Clear();

// Display header
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("=== MAIN MENU ===");
Console.ResetColor();

// Display options
Console.WriteLine("1. Option One");
Console.WriteLine("2. Option Two");
Console.WriteLine("3. Option Three");

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("0. Exit");
Console.ResetColor();

Console.Write("\nEnter your choice: ");

// Get user input
string input = Console.ReadLine();

switch (input)
{
case "1":
DisplayOption("Option One");
break;
case "2":
DisplayOption("Option Two");
break;
case "3":
DisplayOption("Option Three");
break;
case "0":
exit = true;
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid option! Press any key to continue...");
Console.ResetColor();
Console.ReadKey();
break;
}
}
}

static void DisplayOption(string option)
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"You selected: {option}");
Console.ResetColor();
Console.WriteLine("\nPress any key to return to the menu...");
Console.ReadKey();
}
}

4.1.4 - Reading User Input

Reading and processing user input is a fundamental aspect of interactive console applications. C# provides several methods to handle different types of input.

4.1.4.1 - Reading and Parsing Numeric Input

When reading numeric input, you need to parse the string returned by Console.ReadLine() to convert it to the appropriate numeric type.

Example:

using System;

class Program
{
static void Main()
{
// Reading an integer
Console.Write("Enter an integer: ");
string input = Console.ReadLine();

if (int.TryParse(input, out int number))
{
Console.WriteLine($"You entered: {number}");
Console.WriteLine($"Double of your number is: {number * 2}");
}
else
{
Console.WriteLine("That's not a valid integer!");
}

// Reading a decimal number
Console.Write("\nEnter a decimal number: ");
input = Console.ReadLine();

if (double.TryParse(input, out double decimalNumber))
{
Console.WriteLine($"You entered: {decimalNumber}");
Console.WriteLine($"Square of your number is: {decimalNumber * decimalNumber}");
}
else
{
Console.WriteLine("That's not a valid decimal number!");
}
}
}

4.1.4.2 - Handling Different Types of Input

Here's a more comprehensive example that handles different types of input:

using System;

class Program
{
static void Main()
{
// Reading a string
Console.Write("Enter your name: ");
string name = Console.ReadLine();

// Reading an integer with validation
int age = ReadInteger("Enter your age: ", 0, 120);

// Reading a decimal with validation
double height = ReadDouble("Enter your height in meters: ", 0.5, 2.5);

// Reading a boolean (yes/no)
bool likesProgram = ReadBoolean("Do you like this program? (y/n): ");

// Display the collected information
Console.WriteLine("\n--- User Information ---");
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Height: {height:F2} meters");
Console.WriteLine($"Likes Program: {likesProgram}");
}

// Helper method to read an integer with validation
static int ReadInteger(string prompt, int min, int max)
{
int value;
bool isValid;

do
{
Console.Write(prompt);
isValid = int.TryParse(Console.ReadLine(), out value) && value >= min && value <= max;

if (!isValid)
{
Console.WriteLine($"Please enter a valid integer between {min} and {max}.");
}

} while (!isValid);

return value;
}

// Helper method to read a double with validation
static double ReadDouble(string prompt, double min, double max)
{
double value;
bool isValid;

do
{
Console.Write(prompt);
isValid = double.TryParse(Console.ReadLine(), out value) && value >= min && value <= max;

if (!isValid)
{
Console.WriteLine($"Please enter a valid number between {min} and {max}.");
}

} while (!isValid);

return value;
}

// Helper method to read a boolean (yes/no)
static bool ReadBoolean(string prompt)
{
while (true)
{
Console.Write(prompt);
string input = Console.ReadLine().Trim().ToLower();

if (input == "y" || input == "yes")
{
return true;
}
else if (input == "n" || input == "no")
{
return false;
}
else
{
Console.WriteLine("Please enter 'y' or 'n'.");
}
}
}
}

4.1.4.3 - Reading Passwords

When reading sensitive information like passwords, you might want to mask the input:

using System;

class Program
{
static void Main()
{
string username = ReadLine("Enter username: ");
string password = ReadPassword("Enter password: ");

Console.WriteLine($"\nUsername: {username}");
Console.WriteLine($"Password: {new string('*', password.Length)}");
}

// Helper method to read a line of text
static string ReadLine(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}

// Helper method to read a password (masking input)
static string ReadPassword(string prompt)
{
Console.Write(prompt);
string password = "";
ConsoleKeyInfo key;

do
{
key = Console.ReadKey(true); // true means do not display the character

// Ignore control keys like arrows
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password += key.KeyChar;
Console.Write("*"); // Display asterisk instead of the actual character
}
else if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
// Handle backspace
password = password.Substring(0, password.Length - 1);
Console.Write("\b \b"); // Erase the last asterisk
}
} while (key.Key != ConsoleKey.Enter);

Console.WriteLine(); // Add a new line after password input
return password;
}
}

The Console class provides a powerful set of tools for creating interactive command-line applications in C#. By mastering these techniques, you can build user-friendly console applications with formatted output, colorful displays, and robust input handling.