Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-3.5

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.

like image 741
Chris Wenham Avatar asked Jul 18 '11 15:07

Chris Wenham


1 Answers

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

like image 173
Jamiec Avatar answered Oct 04 '22 07:10

Jamiec