Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an object to IEnumerable<T> where T is not known

Tags:

c#

reflection

I am trying to play with Reflection and ran into the following situation.

In the following code, let's assume that the 'obj' can be of types IEnumerable<> or ICollection<> or IList<>.

I would like to cast this System.Object to IEnumerable<> always (as ICollection<> and IList<> inherit from IEnumerable<> anyway), so that i would like to enumerate over the collection and use reflection to write the individual items.

Motivation behind this is I am just trying to see if how would Serializers, in general, serialize data and so I am trying to simulate that situation in the hope to understand Reflection too.

I thought of casting the object to non-generic IEnumerable, but thought that this would cause unnecessary boxing of objects, when let's say the actual instance of IEnumerable<int>...am I thinking right?

private void WriteGenericCollection(object obj)
    {
        Type innerType = obj.GetType().GetGenericArguments()[0];

        //Example: IEnumerable<int> or IEnumerable<Customer>
        Type generatedType = typeof(IEnumerable<>).MakeGenericType(innerType);

        //how could i enumerate over the individual items?
    }
like image 242
Kiran Avatar asked Aug 29 '12 00:08

Kiran


1 Answers

Well, since you don't know the actual type of the items until runtime, you don't need to use the generic IEnumerable<T> interface; just use the non-generic one, IEnumerable (the generic one inherits from it):

private void WriteGenericCollection(object obj)
{
    IEnumerable enumerable = (IEnumerable)obj;
    foreach(object item in enumerable)
    {
        ...
    }
}
like image 187
Thomas Levesque Avatar answered Oct 11 '22 20:10

Thomas Levesque