I am encountering a problem which is how do I convert input strings like "RED" to the actual Color type Color.Red
in C#. Is there a good way to do this?
I could think of using a switch statement and cases statement for each color type but I don't think that is clever enough.
(It would really have been nice if you'd mentioned which
Color
type you were interested in to start with...)One simple way of doing this is to just build up a dictionary via reflection:
That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.
If you want it to be case-insensitive, you can pass in something like
StringComparer.OrdinalIgnoreCase
as an extra argument in theToDictionary
call. You can easily addTryParse
etc methods should you wish.Of course, if you only need this in one place, don't bother with a separate class etc :)
It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:
This worked nicely for my needs ;) Hope someone can use it....
The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)
As far as I can tell,
ColorTranslator.FromHtml
is also.If
Color.FromName
cannot find a match, it returnsnew Color(0,0,0);
If
ColorTranslator.FromHtml
cannot find a match, it throws an exception.UPDATE:
Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:
I've used something like this before:
The simplest way: