tags:

views:

58

answers:

3

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?

+2  A: 

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:

if (x is IList) {
  foreach (object o in (IList)x) {
    // ...
  }
}

(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).

itowlson
I still get: Using the generic type 'System.Collections.Generic.IList<T>'
Casebash
Make sure to add "using System.Collections;" at the top of your file. itowlson's code should work.
Reed Copsey
A: 
if (x.GetType().IsInstanceOfType(typeof(IList<string>)))
{
  foreach (Object o in x) // replace with you type
  { }
}
Asad Butt
The if clause will work, but it will still give him a compiler error on the foreach.
itowlson
And what error is that? It compiles fine on my machine if x = `IList<string> x = new List<string>();`
Asad Butt
Of course it will compile in that snippet, because x is compile-time typed as `IList<string>` already. But the question is about when you (and the compiler) *don't* know if x is a list -- that's why he's having to cast. His scenario is more like `object x = new List<Something>();` -- and the compiler won't let you foreach over x in that case without the cast. (In fact in this case even the if clause will fail because it's a `List<Something>` not a `List<string>`.)
itowlson
Great explanation. Do, appreciate.
Asad Butt
+2  A: 

You can use "as" to save a cast:

var xList = x as IList;
if(x != null) {
    foreach(object o in xList){
      // ...
    }
}
Michael Stum