Get an unknown type list graph

I call a function that returns an object, and in certain circumstances this object will be List.

GetType on this object can give me:

{System.Collections.Generic.List`1[Class1]}

or

{System.Collections.Generic.List`1[Class2]}

etc.

I don’t care that this type, all I want is a graph.

I tried:

Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);

but that gives me an AmbiguousMatchException that I cannot do without knowing the type.

I tried casting for IList, but I get:

Cannot pass an object of type "System.Collections.Generic.List'1 [ClassN]" to enter "System.Collections.Generic.IList'1 [System.Object]".

UPDATE

The Marcs answer below is actually correct. The reason it didn't work for me is because I have:

using System.Collections.Generic;

. , IList ICollection. System.Collections.IList, .

+5
4

ICollection .Count

List<int> list = new List<int>(Enumerable.Range(0, 100));

ICollection collection = list as ICollection;
if(collection != null)
{
  Console.WriteLine(collection.Count);
}
+7

var property = typeof(ICollection).GetProperty("Count");
int count = (int)property.GetValue(list, null);

, .

+3

Use GetProperty instead of GetMethod

0
source

You can do it

var countMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);
0
source

All Articles