Enum.TryParse

From Unify Community Wiki
Jump to: navigation, search

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;
    }
}

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. */
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox