ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Enum<T>.Parse() and Enum<T>.TryParse()

Parses the specified string value into the Enum type passed. Also contains a bool to determine whether or not the case should be ignored.

Source

public static class Enum<T>
{
  public static T Parse(string value)
  {
    return Enum<T>.Parse(value, true);
  }

  public static T Parse(string value, bool ignoreCase)
  {
    return (T)Enum.Parse(typeof(T), value, ignoreCase);
  }

  public static bool TryParse(string value, out T returnedValue)
  {
    return Enum<T>.TryParse(value, true, out returnedValue);
  }

  public static bool TryParse(string value, bool ignoreCase, out T returnedValue)
  {
    try
    {
      returnedValue = (T)Enum.Parse(typeof(T), value, ignoreCase);
      return true;
    }
    catch
    {
      returnedValue = default(T);
      return false;
    }
  }
}

Example

//Enum
public enum MyEnum
{
  Foo,
  Bar,
}

MyEnum a = Enum<MyEnum>.Parse("foo"); //Returns MyEnum.Foo
MyEnum b = Enum<MyEnum>.Parse("foo", false); //Fails as the parse is case sensitive

//Try Parse
MyEnum c = MyEnum.Foo;

if(Enum<MyEnum>.TryParse("Fi", out c) == false)
{
  //throw an error
}

Author: Dan Atkinson

Submitted on: 22 dec. 2009

Language: C#

Type: System.Enum

Views: 17184