Enum.TryParse

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
m (Text replace - "<csharp>" to "<syntaxhighlight lang="csharp">")
m (Text replace - "</csharp>" to "</syntaxhighlight>")
Line 23: Line 23:
 
     /* The parsed  string does not match any enum state, handle failure here. */
 
     /* The parsed  string does not match any enum state, handle failure here. */
 
}
 
}
</csharp>
+
</syntaxhighlight>
  
 
==EnumExtensions.cs==
 
==EnumExtensions.cs==
Line 48: Line 48:
 
      
 
      
 
}
 
}
</csharp>
+
</syntaxhighlight>

Revision as of 20:45, 10 January 2012


Author: Juan Manuel Palacios

Contents

Overview

This script provides an instance TryParse method for .Net's System.Enum class, analogous to the non-exception-throwing TryParse methods that other .Net built-in types provide. As opposed to those, though, this extension method is an instance method, due to the very nature of C# extension methods themselves.

Note that .Net 4.0 does provide an out-of-the-box Enum.TryParse method, but that's currently not available to Unity users as of its 3.4.2 release.

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.


Sample

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

EnumExtensions.cs

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;
    }
 
 
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox