Monday, February 14, 2011 4:20 PM
I have an application that I just want to check the Cont property of List<T> but the object sent in is an Object. So the question is two fold.
1) How do I tell that the object is a List<T>? I can specifically test for List<string> (like if(o is List<string>). But I don't know how to test if it is a generic list?
2) Once I know that the object is a List<T> I want to find out how many there are so I need to cast it to List<T> in order to call Count. Again I am not sure how to do this.
Monday, February 14, 2011 4:56 PM
To define the List as a list of objects [ I do this all the time]:
Define a class with your methods and properties for the class [ Data fields ]
then in the program that is using the class:
List<Rcd> rcds = new List<Rcd>(); // this defines the list to store the Rcd class structure.
// then to use the list...
Rcd r = new Rcd(sql.Reader); // the constructor takes the Sql data Reader object and populates the class
rcds.Add(r); // Adds the Rcd class object to the list of rcds.
Second Question: answer is simple....use the rcds.Length proprty...This will determine the number on entries in rcds array.
Monday, February 14, 2011 5:01 PMModerator
A better option is to just test for ICollection.
Since List<T> implements ICollection, any List<T> (plus many other classes) will return true if they're an ICollection, which will allow you to get a count directly.
int count = 0;
ICollection collection = o as ICollection;
if (collection != null)
count = collection.Count;
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
- Marked As Answer by KevinBurton Monday, February 14, 2011 5:10 PM
Monday, February 14, 2011 5:20 PM
I think you misunderstood my question. I have an object that is presented to me as a type object I need to verify that the object is a List<T> and that the number of items in the list is greater than zero. I think Red Copsey, Jr posted a solution that should work. Thank you.
Monday, February 14, 2011 5:27 PM
You can check if the object is a List<T> with
Type objType = obj.GetType(); bool isList = objType.IsGenericType == true && objType.GetGenericTypeDefinition() != typeof(List<>);
Get the type of the list with
Type itemType = propertyType.GetGenericArguments();
Test for string with
bool itemIsString = itemType == typeof(string);
For Count you cast to IList or ICollection as suggested.
Hope this helps.