Reputation: 6402
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?
Upvotes: 1
Views: 329
Reputation: 136104
You could try using GetTypeInfo
:
using System.Reflection; // to get the extension method for GetTypeInfo()
if(typeof(TEnum).GetTypeInfo().IsEnum)
// whatever
Upvotes: 2
Reputation: 1500465
If Type.IsEnum
isn't supported, you could always use:
if (typeof(TEnum).BaseType != typeof(Enum))
(Assuming BaseType
is available, of course.)
Upvotes: 3