Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a type T of a generic method is IEnumerable<> and loop it?

Tags:

c#

generics

I'd like to do something like this

void DoSomething<T>(T param)
{
    if param is IEnumerable<?>
    {
        loop param and do stuff
    }
}

I don't know what to do in the place of the question mark. And is it possible at all?

like image 573
tranmq Avatar asked Sep 29 '12 02:09

tranmq


1 Answers

What you are looking for is :

if (T is IEnumerable) { .. }

but if you expect T to be IEnumerable all the time you can do:

void DoSomething<T>(T param) where T : IEnumerable
{
    foreach (var t in param) { ... }
}

or checking the type of the values inside the IEnumerable:

public void DoSomething<T,U>(T val) where T : IEnumerable<U>
{
    foreach (U a in val)
    {
    }
}

Without having to worry to check it yourself, the compiler will do it for you, which is one of the nice things of having a static type system and compiler :)

like image 196
Francisco Soto Avatar answered Sep 23 '22 11:09

Francisco Soto