Retrieve the Enum Value from Text


The following function illustrates how to find the Enum value given a text input. If no matches are found, it returns the default Enum value, which is usually the integer 0.
public class Utilities
{   
   public static T ParseEnumWithSpaces(string? valueToParse) where T : struct, IConvertible
   {
      if (typeof(T).IsEnum == false) throw new ArgumentException("T must be an enum type", nameof(T));
      if (string.IsNullOrWhiteSpace(valueToParse)) return default(T);

      // Set the default return value
      T result = default(T);

      // Get the Enum type and the fields associated with the Enum.
      var enumType = typeof(T);
      var fields = enumType.GetFields();

      // make sure we got some fields back
      if (fields != null)
      {
         // Query the fields for an EnumMember value that matches the value passed in.
         // In this case, do a case-insensitive comparison.
         var qry1 = from a in fields
                    where a.GetCustomAttribute()?.Value?.Equals(valueToParse, StringComparison.CurrentCultureIgnoreCase) ?? false
                    select a;

         // Get the first item returned from the search query.
         var tmp1 = qry1.FirstOrDefault();
         if (tmp1 != null)
         {
            // Get the value from the item returned.
            var tmp2 = tmp1.GetValue(null);
            if (tmp2 != null)
            {
               // Get the Enum value
               result = (T)tmp2;
            }
         }
      }

      return result;
   }
}

Related


Last modified by Mohit @ 4/20/2025 1:47:00 PM