-4

Any clue how to define T in this code?

 public static T ToEnum<T>(this string value, T defaultValue)
        {
            if (string.IsNullOrEmpty(value))
            {
                return defaultValue;
            }

            T result;
            return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
        }

Severity Code Description Project File Line Error CS0453 The type 'T' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.TryParse(string, bool, out TEnum)'

NoWar
  • 36,338
  • 80
  • 323
  • 498

1 Answers1

4

Try using a constraint to have a value type which is a struct, for sample:

public static T ToEnum<T>(this string value, T defaultValue)
      where T : struct 
{
    if (string.IsNullOrEmpty(value))
    {
        return defaultValue;
    }

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}

I haven't tested it.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194