How do I get the type of the elements underlying an enumerable object

  • Thread starter Thread starter Hermann Klinke
  • Start date Start date
H

Hermann Klinke

This is what I mean: I have the an enumerable object (implements
IEnumerable => GetEnumerator() method) and I would like to find out
what types underly this enumerable object. For example, if I have the
following:

int[] numbers = new int[] {1,2,3}

I can do this:

foreach(int number in numbers)
{
...
}

I want to find a way to get the type of the elements of the "numbers"
object, which is "int" in this case, because I can enumerate over
"int" objects. I need this to also work if the elements are null.
The construct where I would find out the type of the underlying
elements would look like this:

foreach (object o in enumerableObject)
{
if (o == null)
{
//TODO: find out the actual type of "o" (remember "o" is
null), so I have to somehow use the enumerableObject
}
}
 
Hermann,

Instead of using IEnumerable, why not use the generic version,
IEnumerable<T>. In this case, you would use Nullable<int> for T (or the
alias, int?).

Hope this helps.
 
Back
Top