Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Object to Collection

I have the situation where I am given an object and need to:

  • Determine if that object is a single object or a collection (Array, List, etc)
  • If it is a collection, step though the list.

What I have so far. Testing for IEnumerable does not work. And the conversion to IEnumerable only works for non-primitive types.

static bool IsIEnum<T>(T x)
{
    return null != typeof(T).GetInterface("IEnumerable`1");
}
static void print(object o)
{
    Console.WriteLine(IsIEnum(o));       // Always returns false
    var o2 = (IEnumerable<object>)o;     // Exception on arrays of primitives
    foreach(var i in o2) {
        Console.WriteLine(i);
    }
}
public void Test()
{
    //int [] x = new int[]{1,2,3,4,5,6,7,8,9};
    string [] x = new string[]{"Now", "is", "the", "time..."};
    print(x);       
}

Anyone know how to do this?

like image 834
Johnny Mopp Avatar asked Jan 15 '23 03:01

Johnny Mopp


1 Answers

It is sufficient to check if the object is convertible to the non-generic IEnumerable interface:

var collection = o as IEnumerable;
if (collection != null)
{
    // It's enumerable...
    foreach (var item in collection)
    {
        // Static type of item is System.Object.
        // Runtime type of item can be anything.
        Console.WriteLine(item);
    }
}
else
{
    // It's not enumerable...
}

IEnumerable<T> itself implements IEnumerable and so this will work for generic and non-generic types alike. Using this interface instead of the generic interface avoids issues with generic interface variance: IEnumerable<T> is not necessarily convertible to IEnumerable<object>.

This question discusses generic interface variance in much more detail: Generic Variance in C# 4.0

like image 98
Richard Cook Avatar answered Jan 20 '23 17:01

Richard Cook