Reputation: 24017
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
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
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
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
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