Bibhu Pala
Bibhu Pala

Reputation: 1

Change Console Color by Providing a string

I want to change my Console BackgroundColor based on the color name as a string, like "Red" or "Blue".

This is a rough example:

public void ChangeBackGroundColor(string ColorName)
{
    Console.BackgroundColor = ConsoleColor.ColorName;
    Console.Clear();
}

It should change the BackgroundColor of the Console.

Upvotes: 0

Views: 754

Answers (3)

Jimi
Jimi

Reputation: 32288

Simple variation, using Enum.TryParse() to skip non existing colors:

private static void ChangeBackGroundColor(string ColorName)
{
    if (Enum.TryParse(ColorName, out ConsoleColor Color))
        Console.BackgroundColor = Color;
    Console.Clear();
}

Upvotes: 0

currarpickt
currarpickt

Reputation: 2302

You need to parse the string into ConsoleColor enum type. Enum.Parse will throw exception if ColorName is not represented in ConsoleColor. Therefore, you could use TryParse to prevent the exception and handle it separately.

public void ChangeBackGroundColor(string ColorName)
 {
     ConsoleColor consoleColor;

     if (Enum.TryParse(ColorName, out consoleColor))
     {
         // We now have an enum type.
         Console.BackgroundColor = consoleColor;
         Console.Clear();
     }

     //do whatever you want if it's invalid ColorName    
     Console.WriteLine("invalid color");
 }

Upvotes: 0

Sean
Sean

Reputation: 62532

You need to convert the string ColorName to the appropriate enum value:

Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), ColorName, true);
Console.Clear();

Upvotes: 1

Related Questions