1 Replies - 1706 Views - Last Post: 21 September 2012 - 04:32 AM

#1 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Generic Method To Get Enum Value By String

Posted 21 September 2012 - 04:32 AM

Description: Pass in the string value of the enum element. Set T to the type of the enum.

This snippet uses generics to return an enum value that has been parsed by the string value.

/// <summary>
/// Returns an enum of type T for the given string value.  Returns default if not found or
/// if T is not an enum type.
/// </summary>
/// <typeparam name="T">Enum Type</typeparam>
/// <param name="enumText">String value of enum</param>
/// <returns></returns>
public T GetEnumByText<T>(string enumText) where T : struct, IConvertible
{
    // checks to see if the type is an enum.  if not, return the default for 
    //    the type
    if (!typeof(T).IsEnum)
    {
        return default(T);
    }

    T newEnum;

    Enum.TryParse<T>(enumText, true, out newEnum);

    return newEnum;
}

=====================================

Example code:

TypeCode typeCode = GetEnumByText<TypeCode>("boolean");
Console.WriteLine(typeCode.ToString());
Console.Read();


Is This A Good Question/Topic? 0
  • +

Replies To: Generic Method To Get Enum Value By String

#2 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Generic Method To Get Enum Value By String

Posted 21 September 2012 - 04:32 AM

Description: Pass in the string value of the enum element. Set T to the type of the enum.

This snippet uses generics to return an enum value that has been parsed by the string value.

/// <summary>
/// Returns an enum of type T for the given string value.  Returns default if not found or
/// if T is not an enum type.
/// </summary>
/// <typeparam name="T">Enum Type</typeparam>
/// <param name="enumText">String value of enum</param>
/// <returns></returns>
public T GetEnumByText<T>(string enumText) where T : struct, IConvertible
{
    // checks to see if the type is an enum.  if not, return the default for 
    //    the type
    if (!typeof(T).IsEnum)
    {
        return default(T);
    }

    T newEnum;

    Enum.TryParse<T>(enumText, true, out newEnum);

    return newEnum;
}

=====================================

Example code:

TypeCode typeCode = GetEnumByText<TypeCode>("boolean");
Console.WriteLine(typeCode.ToString());
Console.Read();

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1