Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is an IEnumerable of some sort

People also ask

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

What is IEnumerable <>?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.


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

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...
    }
}

The other answers have pointed out the generic/non-generic IEnumerable difference but I should also point out that you will also want to test for String specifically because it implements IEnumerable but I doubt you'll want to treat it as a collection of characters.


Since C# 7.0 you can also achieve this so:

if (variable is IEnumerable enumVar)
{
    foreach (var e in enumVar)
    {
        ...
    }
}

Well, somewhat simple but... if you only have:

using System.Collections.Generic;

you might need to add:

using System.Collections;

The former defines IEnumerable<T> and latter defines IEnumerable.


You can actually test the base class of any generic type directly.

instance.GetGenericTypeDefinition()  == typeof(IEnumerable<>)