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've used something like this before:
public static T CreateFromString(string stringToCreateFrom) {
T output = Activator.CreateInstance();
if (!output.GetType().IsEnum)
throw new IllegalTypeException();
try {
output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
}
catch (Exception ex) {
string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
_logger.Error(error, ex);
throw new IllegalArgumentException(error, ex);
}
return output;
}