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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With