I am calling a function that returns an object and in certain circumstances this object will be a List.
A GetType on this object might gives me:
{System.Collections.Generic.List`1[Class1]}
or
{System.Collections.Generic.List`1[Class2]}
etc
I don't care what this type is, all I want is a Count.
I've tried:
Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);
but this gives me an AmbiguousMatchException which I can't seem to get around without knowing the type.
I've tried casting to IList but I get:
Unable to cast object of type 'System.Collections.Generic.List'1[ClassN]' to type 'System.Collections.Generic.IList'1[System.Object]'.
UPDATE
Marcs answer below is actually correct. The reason it wasn't working for me is that I have:
using System.Collections.Generic;
at the top of my file. This means I was always using the Generic versions of IList and ICollection. If I specify System.Collections.IList then this works ok.