Parse string value to add to enum List
I want parse a string so it can be added to a List of enum.
ex.
enum Directions {North,East, South West}
List directions;
string s = "North" directions.Add(s);
Answer by Bunny83 · Mar 28, 2018 at 09:55 PM
You would use System.Enum.Parse() for this. Just do this:
Directions dir = (Directions)System.Enum.Parse(typeof(Directions), s);
directions.Add(dir);
Note that you may want to rename your enum to "Direction" since a value of type "Direction" represents one direction and not multiple. That's why Unity's KeyCode enum is called KeyCode and not KeyCodes. It's just a general convention since it makes more sense.
Answer by KDamen · Mar 28, 2018 at 08:31 PM
Hello @MadsWiering,
What is the reason you want to do this. I need some context with your question.
Because an enum is a integer value, an enum can be seen like this:
enum Directions {
NORTH = 0,
EASY = 1,
SOUTH = 2,
WEST = 3
};
Maybe if the context is clear, I can help you with another solution. How I read your question, you could use a Dictionary.
Dictionary Directions = new Dictionary();
Directions.Add("North", 1);
Directions.Add("South", 2);
Directions.Add("West", 3);
Directions.Add("East", 4);
Sorry if I use bad english.
Hope that my answer has helped you.
Your answer
Follow this Question
Related Questions
Help int.Parse "Input String was not in the correct format" PROBLEM 0 Answers
How do check which enum value was selected? 2 Answers
Error FormatException: Input string was not in a correct format. 0 Answers
\n Not picked up when reading string from file's name 1 Answer
I am getting this error when i try to parse a string to get float value. 0 Answers