I have the situation where I am given an object and need to:
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?
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
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