Click here to Skip to main content
15,895,777 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
Hey i have Writen a Code in COnsole Application in which user have to Enter a Color name and when it press enter and write something forground color will be the enter color by user.

MIDL
Console.WriteLine("Enter the Name of Color in Which do You Want to Print");
                  string str = Console.ReadLine();

                  Console.ForegroundColor = (ConsoleColor) str;


but it gives error Error:- Cannot convert type 'string' to 'System.ConsoleColor'
any idea how can i convert string to System.ConsoleColor
Posted
Updated 24-Sep-17 11:17am

ShilpaKumario wrote:
Console.ForegroundColor = (ConsoleColor) str;

As you may easily find yourself reading the documentation[^], you should use:

(ConsoleColor) Enum.Parse(typeof(ConsoleColor), str);

:)
 
Share this answer
 
While several people (4 so far) have answered your question, you'd be better off not doing it this way. There may be typos when you ask users to type in the name of color. A better option would be to give them a list of colors and ask them to choose from that list. I assume the code snippet you showed was for test purposes and that your actual code has some kind of proper UI.
 
Share this answer
 
Console.WriteLine("Enter the Name of Color in Which do You Want to Print");
           string str = Console.ReadLine();
           Console.ForegroundColor =(ConsoleColor) Enum.Parse(typeof(ConsoleColor), str,true);
           Console.Read()
 
Share this answer
 
You can solve this error by using Enum.Parse property take a look how it will works for you

MIDL
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), str);
 // Parse is used to convert value to equivalent enumerated object.
 
Share this answer
 
Well, there are various ways to get color for a given string. One of them:
C#
ColorConverter conv = new ColorConverter();
conv.ConvertFromString("Red");

try!
 
Share this answer
 
Comments
MDNadeemAkhter 25-Oct-10 8:26am    
ColorConverter class is of System.Drawing namespace and as i know in Console Class System.Drawing namespace is not access by default. thats why not a good answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900