How to check if a variable is an IEnumerable of some sort

Earlz picture Earlz · Jan 4, 2011 · Viewed 35.4k times · Source

basically I'm building a very generic T4 template and one of the things I need it to do is say print variable.ToString(). However, I want it to evaluate lists and foreach through them and instead print ListItem.ToString() My T4 template does not know what type variable will be ahead of time, that is why this is so generic.

But my current code that gets generated looks like this:

if(variable!=null)
  if(variable is IEnumerable) //error here
    foreach(var item in variable)
      Write(item.ToString());

I get a compiler error on the marked line for "Using the generic type System.Generic.Collections.IEnumerable requires one type argument"

I don't actually care what type it is though, I just want to know if you can foreach through the variable. What code should I use instead?

Answer

user164771 picture user164771 · Jan 4, 2011

You have already accepted an answer however,since generic IEnumerable<T> implements the non generic IEnumerable you can just cast to that.

// Does write handle null? Might need some sanity aswell.

var enumerable = variable as System.Collections.IEnumerable; 

if (enumerable != null)
    foreach(var item in enumerable)
         Write(item);
else
    Write(item);