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.
Cast it to ICollection and use that .Count
using System.Collections;
List<int> list = new List<int>(Enumerable.Range(0, 100));
ICollection collection = list as ICollection;
if(collection != null)
{
Console.WriteLine(collection.Count);
}
You could do this
var property = typeof(ICollection).GetProperty("Count");
int count = (int)property.GetValue(list, null);
assuming you want to do this via reflection that is.
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