c# console color text

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

    C# Console Color Text

    Changing the color of text in the console is a common requirement in C# applications, especially in situations where you want to highlight certain outputs or differentiate between types of messages. C# provides a straightforward way to modify the foreground and background colors of console text using the ConsoleColor enumeration. This article will guide you through the process of changing text colors in the console using C#.

    Changing Text Color in Console

    Setting Foreground and Background Colors

    The Console.ForegroundColor and Console.BackgroundColor properties allow you to set the text color and background color respectively. These properties accept values from the ConsoleColor enumeration which includes colors like Red, Blue, Yellow, Green, and more.

    Example: Using ForegroundColor and BackgroundColor

    Here’s how you can use these properties to change the console text color:

     

    using System;
    
    public class ConsoleColorExample
    {
        public static void Main()
        {
            // Set the foreground color to red
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("This is red text");
    
            // Set the foreground color to green
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("This is green text");
    
            // Set the background color to blue
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This is white text on a blue background");
    
            // Reset the console colors to their defaults
            Console.ResetColor();
            Console.WriteLine("Back to default colors.");
        }
    }
    

    Resetting Console Colors

    It’s important to reset the console colors to their defaults after you change them. This can be done using the Console.ResetColor() method, which resets both foreground and background colors to their original settings.

    Best Practices

    • Reset Colors: Always reset console colors to their defaults to avoid unintended color changes in later output.
    • Readability: Choose text and background colors that ensure readability. For example, dark text on a dark background can be hard to read.
    • Conditional Coloring: Use different colors based on conditions, such as errors or warnings, to enhance the information's clarity.

    Conclusion

    Using color in console applications can help make the output more understandable and distinguish between different types of information. The ConsoleColor properties in C# provide an easy and effective way to enhance your console applications with colored text.

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments