c# console color codes

c# console color codes
In this article [Show more]

    C# Console Color Codes

    In C#, changing the console text color can make the output clearer and more engaging. The Console class provides two properties, Console.ForegroundColor and Console.BackgroundColor, that allow you to modify text and background colors using ConsoleColor enumeration values. This article explores how to use these color codes to enhance your console applications.

    ConsoleColor Enumeration

    The ConsoleColor enumeration defines 16 different colors:

    • Black
    • DarkBlue
    • DarkGreen
    • DarkCyan
    • DarkRed
    • DarkMagenta
    • DarkYellow
    • Gray
    • DarkGray
    • Blue
    • Green
    • Cyan
    • Red
    • Magenta
    • Yellow
    • White

    Example: Changing Console Text and Background Colors

    Using Foreground and Background Colors

     

    using System;
    
    public class ConsoleColorCodesExample
    {
        public static void Main()
        {
            // Set text color to Green
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("This text is green!");
    
            // Set text color to Red
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("This text is red!");
    
            // 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 to default console colors
            Console.ResetColor();
            Console.WriteLine("Back to default colors.");
        }
    }
    

    Key Tips and Best Practices

    • Contrast: Ensure that the text color contrasts well with the background for good readability.
    • Reset Colors: Use Console.ResetColor() to restore the default console colors and avoid unintended changes.
    • Conditional Coloring: Use different colors for various message types (e.g., errors in red, information in green).

    Conclusion

    Using color codes in C# console applications can improve the readability and organization of your output. By leveraging the Console.ForegroundColor and Console.BackgroundColor properties, you can apply these color codes effectively.


     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments