- Home /
Converting a string to an enum
Hi! I need to convert a string into its equivalent enum object. Although I could make an auxiliary function to do that, I wonder if C# can do that for me and I've found this article, but I'm afraid it doesn't work in Unity.
I've been searching here through Unity Answers but haven't been able to find a solution, can you help me?
Thanks in advance!
That does work. Let me see if I can find an example for you.
Yes, sorry about being a little bit vague. I should have mentioned I was getting a compilation error because I was trying to use it exactly as it appeared in the article (i.e., by using Enum.Parse). I tried the solution that taoa suggested and it worked! Thanks for your reply!
Answer by taoa · Mar 14, 2011 at 01:09 PM
YourEnumType parsed_enum = (YourEnumType)System.Enum.Parse( typeof(YourEnumType), your_string );
This works!
@Anxowtf
The initial string goes into the 'your_string' variable in the example code above. The function then looks for an entry in the specified enumeration that matches the given string and returns it.
Imagine the opposite of enum.ToString().
I found I also needed to convert as in the code below:
YourEnumType parsed_enum = (YourEnumType)System.Enum.Parse( typeof( YourEnumType ), your_string );
I got an error. This fix it:
YourEnumType yourEnum = (YourEnumType) System.Enum.Parse (typeof (YourEnumType), yourString);
hmmm correct me if im wrong, but this is the exact same code as he wrote
Answer by Pro-senik · Feb 21, 2019 at 06:31 PM
Another option with detecting parse error would be:
if( System.Enum.TryParse<YourEnumType>(yourString, out YourEnumType yourEnum) )
{
... if string was correctly parsed, you can now use yourEnum variable
}
You've written the function call (partly) like a declaration. It should be
YourEnumType yourEnum;
if( System.Enum.TryParse<YourEnumType>(yourString, out yourEnum) )
{
}
As of C# 7.0 the ability to declare a variable right at the point where it is passed as an out argument was introduced.
Apologies, I didn't know that, that's a good development. How do I go about using it in Unity? Do I need to move to .Net 4 or something? I see that 3.5's on the way out so I guess that's a good idea anyway
Shouldn't it also work like this:
if( System.Enum.TryParse(yourString, out YourEnumType yourEnum) )
Or did the adhoc variable declaration break the generic type inference features of the compiler? ^^
You are correct, it can be simplified like this. I just wanted to implicitly show the whole struct of the method for better understanding.
Your answer

Follow this Question
Related Questions
How would you convert string to enum 1 Answer
String Assets? 1 Answer
Parsing String from script A into Enum in script B 1 Answer
Cast the result of an enum as a string 3 Answers
Converting enum to string ? 1 Answer