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

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
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top