I have a method that takes as an input parameter an object of type IEnumerable
. I want to enumerate the enumeration and for each item use reflection to get the value for each property.
I have the following code:
protected void WriteData(IEnumerable data)
{
var enumerationTypeInfo = data.GetType();
var itemTypeInfo = enumerationTypeInfo.GetElementType();
...
}
The problem is enumerationTypeInfo.GetElementType()
always returns null
. In particular, I'm passing in a List<Entry>
into WriteData
, where Entry
is a class I created. When I use the debugger and set a breakpoint I can see that enumerationTypeInfo
correctly shows that it's a List of type Entry
, but why does GetElementType
return null
?
Thanks
GetElementType
is for use with arrays, not other generic classes. To get a generic type's generic parameters, you can useType.GetGenericArguments
.GetElementType()
returns the element type of arrays.List<T>
is not an array type, and therefore has no "element type."If you want to get the type of elements a random
IEnumerable<T>
produces, try something like this:Note that types can implement more than one version of the same generic interface; a type can implement both
IEnumerable<int>
andIEnumerable<string>
for example. How you handle that case is up to you. The method I provide will take whichever interface type the runtime hands it first.See an example using the above method on ideone.