1

I'm trying to convert a string to an Enum, in a generic way, in a portable class Library

Targes are: .NET 4.5, Windows 8, Windows Phone 8.1, Windows Phone Silverlight 8

I have this string extension, which I've previous used in a Winform application. But in this library it does not compile. It is the line if (!typeof(TEnum).IsEnum) that doesn't work

public static class StringExtensions
{        

    public static TEnum? AsEnum<TEnum>(this string value) where TEnum : struct,  IComparable, IFormattable
    {
        if (!typeof(TEnum).IsEnum)
            throw new ArgumentException("TEnum must be an enumerated type");

        TEnum result;
        if (Enum.TryParse(value, true, out result))
            return result;

        return null;
    }
 }

So my question is: In the given context how do I test for a given type is an enum?

Jens Borrisholt
  • 6,174
  • 1
  • 33
  • 67

2 Answers2

3

If Type.IsEnum isn't supported, you could always use:

if (typeof(TEnum).BaseType != typeof(Enum))

(Assuming BaseType is available, of course.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You could try using GetTypeInfo:

using System.Reflection; // to get the extension method for GetTypeInfo()    

if(typeof(TEnum).GetTypeInfo().IsEnum)
  // whatever
Jamiec
  • 133,658
  • 13
  • 134
  • 193