How to check if a variable is an IEnumerable of some sort
If you want to test for the non-generic IEnumerable
then you'll need to include a using System.Collections
directive at the top of your source file.
If you want to test for an IEnumerable<T>
of some kind then you'll need something like this instead:
if (variable != null)
{
if (variable.GetType().GetInterfaces().Any(
i => i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
// foreach...
}
}
You have already accepted an answer however,since generic IEnumerable<T>
implements the non generic IEnumerable
you can just cast to that.
// Does write handle null? Might need some sanity aswell.
var enumerable = variable as System.Collections.IEnumerable;
if (enumerable != null)
foreach(var item in enumerable)
Write(item);
else
Write(item);