Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Type of IEnumerable object

Tags:

c#

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?

like image 270
countunique Avatar asked Jan 14 '23 00:01

countunique


2 Answers

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]
like image 178
SLaks Avatar answered Jan 21 '23 17:01

SLaks


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).

like image 28
p.s.w.g Avatar answered Jan 21 '23 16:01

p.s.w.g