how to change text color in c#

how to change text color in c#
In this article [Show more]

    How to Change Text Color in C#

    In C#, changing the color of text displayed in the console can enhance the readability of output or provide visual cues during the execution of command-line applications. This article provides an overview of how to change text color using the Console class and offers practical examples.

    Changing Console Text Color

    The Console class in the System namespace has two properties, ForegroundColor and BackgroundColor, that control the color of the text and the console background, respectively.

    Setting the Foreground and Background Colors

    You can set these properties to any value from the ConsoleColor enumeration, which includes basic colors like Red, Green, and Yellow.

     

    using System;
    
    public class TextColorExample
    {
        public static void Main()
        {
            // Setting the foreground color to Yellow
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("This text is yellow!");
    
            // Setting the background color to Blue
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("White text on a blue background!");
    
            // Reset to the default colors
            Console.ResetColor();
            Console.WriteLine("Default colors restored.");
        }
    }
    

    Resetting Console Colors

    After changing the text or background color, it's essential to restore the default console colors. This is done using the Console.ResetColor method.

    Practical Applications

    • Error Messages: Highlight errors in red to make them stand out during troubleshooting.
    • Information or Warnings: Use yellow for warnings or green for informational messages to provide a visual distinction.
    • User Prompts: Improve user prompts by using unique colors to guide user input.

    Best Practices

    • Readable Colors: Ensure the foreground and background colors contrast well for better readability.
    • Consistent Theme: Maintain a consistent color theme throughout the application to improve the user experience.

    Conclusion

    Changing text color in C# using the Console class is a simple yet effective way to enhance the visual appeal and clarity of console applications. By leveraging these color properties, developers can create intuitive and visually distinct user interfaces for command-line tools.


     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments