Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object to IEnumerable<object>?

Tags:

c#

casting

How can I cast an object to IEnumerable<object>?

I know that the object implements IEnumerable<object> but I don't know what type it is. It could be an array, a List<T>, or whatever.


A simple test case I'm trying to get working:

static void Main(string[] args)
{
    object arr = new[] { 1, 2, 3, 4, 5 };
    foreach (var item in arr as IEnumerable<object>)
        Console.WriteLine(item);
    Console.ReadLine();
}
like image 869
mpen Avatar asked Jan 08 '11 04:01

mpen


1 Answers

I ran into the same issue with covariance not supporting value types, I had an object with and actual type of List<Guid> and needed an IEnumerable<object>. A way to generate an IEnumerable when just IEnumerable isn't good enough is to use the linq Cast method

((IEnumerable)lhsValue).Cast<object>()
like image 184
BrandonAGr Avatar answered Sep 20 '22 18:09

BrandonAGr