Search code examples
c#.net-3.5

What's the quickest way to test if an object is IEnumerable?


Is there a quick way to find out if an object variable's contents supports IEnumerable? Specifically I'm using XPathEvaluate() from System.Xml.XPath, which can return "An object that can contain a bool, a double, a string, or an IEnumerable."

So after executing:

XDocument content = XDocument.Load("foo.xml");
object action = content.XPathEvaluate("/bar/baz/@quux");
// Do I now call action.ToString(), or foreach(var foo in action)?

I could poke around with action.GetType().GetInterface(), but I thought I'd ask if there's a quicker/easier way.


Solution

  • You are looking for the is operator:

    if(action is IEnumerable)
    

    or even better, the as operator.

    IEnumerable enumerable = (action as IEnumerable);
    if(enumerable != null)
    {
      foreach(var item in enumerable)
      {
        ...
      }
    }
    

    Note that string also implements IEnumerable, so you might like to extend that check to if(enumerable != null && !(action is string))