Enum.TryParse
From Unify Community Wiki
(Difference between revisions)
Isaiah Kelly (Talk | contribs) (Improved formatting and updated .Net 4.0 support notice.) |
Isaiah Kelly (Talk | contribs) m (Isaiah Kelly moved page EnumExtensions to Enum.TryParse: Much better description of the actual extension method.) |
Latest revision as of 20:06, 7 February 2019
Notice: The latest version of Unity supports .Net 4.0 which provides a builtin Enum.TryParse method.
This script provides a TryParse method for the .Net (3.0 or earlier) System.Enum class, analogous to the non-exception-throwing TryParse methods that other .Net built-in types provide. However this extension method is an instance method, due to the very nature of C# extensions.
using UnityEngine; using System; using System.ComponentModel; public static class EnumExtensions { public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue) { returnValue = default(T); if (Enum.IsDefined(typeof(T), valueToParse)) { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); returnValue = (T)converter.ConvertFromString(valueToParse); return true; } return false; } }
[edit] Usage
Put the EnumExtensions.cs script in the Extensions folder in your Unity project and use the resulting instance TryParse method according to the code sample below.
SomeEnum parsedState; if (parsedState.TryParse<SomeEnum>(aString, out parsedState)) { /* The parsed string matches an enum state, proceed successfully here. */ } else { /* The parsed string does not match any enum state, handle failure here. */ }