Chris Wenham
Chris Wenham

Reputation: 24017

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.

Upvotes: 14

Views: 20706

Answers (6)

Gaizko Antona
Gaizko Antona

Reputation: 1

I am receiving an array of sql parameters, lots of them are Enum Values.

The only way to check if an element is part of an enum has been:

 if(parameterArrayList[0].Value.GetType().BaseType.Name == "Enum")
     Console.WriteLine("Yeah");
 else
     Console.WriteLine("Meh");

Upvotes: -3

Jamiec
Jamiec

Reputation: 136074

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

Upvotes: 35

nWorx
nWorx

Reputation: 2155

try this one

if(action is IENumerable)
{
  //do some stuff
}

hth

Upvotes: 0

Mike
Mike

Reputation: 980

If you just need to test if an object is of a type then use is. If you need to use that object after use as so that the runtime must only do the cast once:

IEnumerable e = action as IEnumerable

if(null != e)
{
    // Use e.
}

Upvotes: 2

Ondra
Ondra

Reputation: 1647

This should work.

    action is IEnumerable;

Upvotes: 0

Oded
Oded

Reputation: 498904

Use the is operator:

if(action is IEnumerable)

This is what it does:

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

Upvotes: 2

Related Questions