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?
}
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)
{
...
}
}
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