views:

58

answers:

3
+3  A: 

Cast it to ICollection and use that .Count

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

ICollection collection = list as ICollection;
if(collection != null)
{
  Console.WriteLine(collection.Count);
}
Marc
Don't I still need a type <T> though?
Chris Simpson
maybe I'm doing something wrong but this gives me: Error 1 Using the generic type 'System.Collections.Generic.ICollection<T>' requires '1' type arguments
Chris Simpson
@Chris, List<T> directly implements ICollection (non-generic) which has a `.Count` property. No type required. Added sample code for clarity.
Marc
@Chris, I tried to make it a completely stand-alone example, hope that helps.
Marc
I'm curious: Did Marc's suggestion work?
S.C. Madsen
If I specify System.Collections.ICollection or System.Collections.IList - this actually works now. Because I had using System.Collections.Generic; it was using the generic versions of these interfaces. Thanks
Chris Simpson
Good job Marc!Chris, please mark as solution, so I can find it if I ever bump into this (I use List<T> all the time in my code, so....)
S.C. Madsen
@S.C. Madsen - Done
Chris Simpson
A: 

Use GetProperty instead of GetMethod

jgauffin
this returns a null
Chris Simpson
+2  A: 

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.

Brian Rasmussen
I like this, but this only works when the list actually _is_ an ICollection type. I don't think this is always the case in the OP's question.
Marc
Admittedly it is a bit hard to tell, but since the examples given are both `List<T>` this works for the given cases. However, looking at the accepted answer it seems there's really no reason to use reflection in this case. If reflection isn't needed it is much easier to just cast to the appropriate type.
Brian Rasmussen