Enhancing C# Console Output with `Console.ForegroundColor`

Learn how to customize the color of your console output in C# using the `Console.ForegroundColor` property. This tutorial demonstrates how to change text color using the `ConsoleColor` enumeration, improving the readability and visual appeal of your console applications.



Using C#'s `Console.ForegroundColor` Property

The C# `Console.ForegroundColor` property controls the color of text written to the console. This is a simple yet effective way to enhance the visual presentation of console applications, making output more readable and informative.

Understanding `Console.ForegroundColor`

The `Console.ForegroundColor` property (part of the `System.Console` class) allows you to change the color of text printed to the console window. The default color is typically grey. You set the color using a member of the `ConsoleColor` enumeration (e.g., `ConsoleColor.Red`, `ConsoleColor.Green`, `ConsoleColor.Blue`).

`Console.ForegroundColor` Syntax


Console.ForegroundColor = ConsoleColor.ColorName;

Replace `ColorName` with the desired color from the `ConsoleColor` enumeration (e.g., `ConsoleColor.Red`, `ConsoleColor.Green`, etc.).

Example 1: Changing Console Text Color


using System;

public class ConsoleColorExample {
    public static void Main(string[] args) {
        Console.WriteLine("Default color text.");
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Red text.");
        Console.ResetColor(); // Reset to default color
        Console.WriteLine("Default color text again.");
    }
}

Example 2: Console-Based Chat Application

This example demonstrates a simple console-based chat application where each user's messages are displayed in their assigned color:


using System;
using System.Collections.Generic;

public class ConsoleChat {
    public static void Main(string[] args) {
        Dictionary<string, ConsoleColor> userColors = new Dictionary<string, ConsoleColor>();
        // ... (code to get user names and colors, then handle chat messages using ForegroundColor) ...
    }
    // ... (SelectColor method) ...
}