user2081994
user2081994

Reputation: 15

Is it possible to parse a string into ConsoleColor in C#

string example = "Red"
if (example == "Red")
{
    Console.ForegroundColor = ConsoleColor.example;
}

Is there any way to do this?

Upvotes: 0

Views: 440

Answers (2)

elvira.genkel
elvira.genkel

Reputation: 1333

You need to parse value using Enum.Parse

string example = "Red"
  if (example == "Red")
  {    
    ConsoleColor consoleColor = ConsoleColor.White;
    try
    {
      consoleColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), example , true);
    }
    catch (Exception)
    {
        //Invalid color
    }

  Console.ForegroundColor = consoleColor ;
}

Upvotes: 1

Carlos Garcia
Carlos Garcia

Reputation: 2970

You can do this:

string example = "Red"
if (example == "Red")
{
     ConsoleColor consoleColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), "Red");
     Console.ForegroundColor = consoleColor;
}

Upvotes: 1

Related Questions