Search code examples
c#colorsbackgroundconsoleforeground

Is there a way to set a ConsoleColor value equal to a variable?


I am working on creating a class to support a console app I am developing, and I would like to create a method within to change both the background and foreground color. Is there a way to set a ConsoleColor value (which I believe is an enum) to another variable so this can easily be changed by the user at runtime? For instance, I am hoping for something like the following.

Public class ConsoleOutput
{
  private var consoleBackground = ConsoleColor.White;
  private var consoleForeground = ConsoleColor.Black;
  
  Public ConsoleOutput
  {
    Console.BackgroundColor = consoleBackground
    Console.ForegroundColor = consoleForeground
  }
}

This, however, did not work.


Solution

  • You don't seem to ever write to the console in your program, which you obviously need to do. Other then that you also need a way to change the colors during runtime using e.g. setters or a function like ChangeColors().

    Here a working sample program for reference:

    namespace MyProgram;
    
    class Program
    {
        static void Main(string[] args)
        {
            var coloredPrinter = new ColoredPrinter(ConsoleColor.White, ConsoleColor.Blue);
            coloredPrinter.WriteLine("This is white text on blue background");
            coloredPrinter.ChangeColors(ConsoleColor.Yellow, ConsoleColor.Red);
            coloredPrinter.WriteLine("This is yellow text on red background");
            Console.WriteLine("This is the default");
        }
    }
    
    class ColoredPrinter
    {
        public ConsoleColor ForegroundColor { get; set; }
        public ConsoleColor BackgroundColor { get; set; }
    
        public ColoredPrinter(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
        {
            ChangeColors(foregroundColor, backgroundColor);
        }
    
        public void ChangeColors(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
        {
            ForegroundColor = foregroundColor;
            BackgroundColor = backgroundColor;
        }
    
        public void WriteLine(string text)
        {
            Console.ResetColor();
            Console.BackgroundColor = BackgroundColor;
            Console.ForegroundColor = ForegroundColor;
            Console.WriteLine(text);
            Console.ResetColor();
        }
    }
    
    

    This prints out the following:

    colored console output