I am trying to determine if an object x is a list. It may be a list of any type and with any generic parameter.
If it is, then I want to iterate over it if it is. This is the best I could come up with, but it fails due to a compilation error
if(x is List){
foreach(Object o in (List)x){
;
}
}
How can I do this?
The easiest way is to cast to IList. This is a non-generic interface and could be implemented by non-generic lists (such as ArrayList) but I’m guessing that won’t be a concern for you:
(And if all you need to do is foreach, you don’t even need IList: IEnumerable will suffice.)
Note that the non-generic IList and IEnumerable are in the System.Collections namespace, which is not using-ed by default. So you will need to add
using System.Collections;(thanks to Reed Copsey for noting this).