This issue came up when trying to answer this question:
https://stackoverflow.com/questions/12434634
The documentation for the Type.IsEnum property says:
If the current Type represents a type parameter in the definition of a generic type or generic method, this property always returns false.
Yet I am not seeing this behavior. typeof(T).IsEnum is returning true. Why? Am I misinterpreting the documentation?
Sample code:
using System;
static class Program
{
public static void Test<TEnum>() where TEnum : struct
{
Console.WriteLine(typeof(TEnum).IsEnum);
}
public static void Test<TEnum>(this string text) where TEnum : struct
{
if (!typeof(TEnum).IsEnum)
{
Console.WriteLine("Not an enum");
return;
}
Console.WriteLine("Is an enum");
}
public enum Test1
{
Value1,
Value2,
}
public enum Test2 : byte
{
Value3,
Value4,
}
static void Main(string[] args)
{
Test<Test1>();
Test<Test2>();
"".Test<Test1>();
"".Test<Test2>();
}
}
The result I get is:
True
True
Is an enum
Is an enum
After reading the documentation for the Type.IsEnum property, I expect the results to be:
False
False
Not an enum
Not an enum
The documentation is talking about the type object that represents the type parameter of an open generic type or method. In your code, you are querying the type object that represents the type argument in the closed generic method, and in your example, of course, that type argument is an enum type.
In other words, the document is talking about the type you would get from calling GetGenericArguments on
typeof(List<>), not ontypeof(List<SomeEnum>).