For most objects I can do,
obj.getType().FullName
But for the following code,
static void Main(string[] args)
{
IEnumerable<int> em = get_enumerable();
Console.WriteLine(em.GetType());
Console.Read();
}
static IEnumerable<int> get_enumerable()
{
for (int i = 0; i < 10; i++)
{
yield return i;
}
}
Output is,
ConsoleApplication1.Program+d__0
Where ConsoleApplication1 is assembly and Program is containing class (not shown). Why doesn't it show IEnumerable and how can I make the GetType more descriptive for this case?
IEnumerable<T>
is an open generic type. It isn't an actual type; it's merely a function that constructs concrete (closed) generic types like IEnumerable<int>
.
IEnumerable<int>
is an interface; it is impossible to have an instance of an interface.
Your iterator function actually returns an instance of a hidden compiler-generated class that implements IEnumerable<int>
; that's what you're seeing from GetType()
.
You want to find the generic type parameter of the type's IEnumerable<T>
implementation:
em.GetType().GetInterface("System.Collections.Generic.IEnumerable`1")
.GetGenericArguments()[0]
IEnumerable
is an interface, but GetType
will return the System.Type
that represents the class of the object, not the interface(s) it implements.
When you use yield return
, the C# compiler automagically generates a new class (named ConsoleApplication1.Program+d__0
in this case) which implements IEnumerable<int>
(and IEnumerable
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With