Chris Simpson
Chris Simpson

Reputation: 8000

Get the Count of a List of unknown type

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.

Upvotes: 11

Views: 10702

Answers (5)

Marc
Marc

Reputation: 9354

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);
}

Upvotes: 21

Karthik
Karthik

Reputation: 1

This could help...

        if (responseObject.GetType().IsGenericType)
        {
            Console.WriteLine(((dynamic) responseObject).Count);
        }

Upvotes: 0

Maxim Trushin
Maxim Trushin

Reputation: 121

You can do this

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

Upvotes: 0

Brian Rasmussen
Brian Rasmussen

Reputation: 116421

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.

Upvotes: 3

jgauffin
jgauffin

Reputation: 101150

Use GetProperty instead of GetMethod

Upvotes: 0

Related Questions