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.

2 Answers

2

YourEnumType parsed_enum = (YourEnumType)System.Enum.Parse( typeof(YourEnumType), your_string );

This works!

where does the string go?

@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 );

how do you know if it failed?

@M0rph3v5 Enum.Parse throws an exception if it fails. If you don't want to add exception-handling you can also use Enum.TryParse and check the return value.

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) ) { }

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? ^^