Search code examples
c#.netreflectiontypesilist

Why can't I find the GetEnumerator() method on the IList type through reflection?


This code is of course valid. IList by definition, has a GetEnumerator() method.

System.Collections.IList list = new List<string>();
System.Collections.IEnumerator ienum = list.GetEnumerator();

However none of the following are able to find a member of the IList type with the name GetEnumerator.

Type iListType= typeof(System.Collections.IList);
var member = iListType.GetMember("GetEnumerator");
var members = iListType.GetMembers().Where(x => x.Name == "GetEnumerator");
var method = iListType.GetMethod("GetEnumerator");
var methods = iListType.GetMethods().Where(x => x.Name == "GetEnumerator");

Solution

  • You can't find GetEnumerator on the IList type, because the IList type does not declare GetEnumerator. IList extends IEnumerable which declares it. So you need to change your code to look for GetEnumerator on the IEnumerable type.

    Type type = typeof(System.Collections.IEnumerable);
    var member = type.GetMember("GetEnumerator");