Ash
Ash

Reputation: 6035

How do I check if a C# generic type is a collection (IEnumerable)?

I'm trying to create a method with generic parameters:

public List<DTListItem> MapDTListResponse(List<App.Order.DT> dtList)
{
    return dtList.Select(MapDTListResponse).ToList();
}

public DTListItem MapDTListResponse(App.Order.DT dt)
{
    return RecMap<DTListItem, App.Order.DT>(dt);
}

private T RecMap<T,TU>(TU newObject)
{
    if (TU is IEnumerable) // this doesn't work; what do i check for here
    {
        //Also, how do i get this bit to replicate MapDTListReponse
        newObject.Select(RecMap).ToList();  
    } 
    else 
    {
        return Mapper.Map<T>(newObject);
    }            
}

As you can see, the first method takes and returns a collection and simply calls the second method (having the same name but different signature) for each element in the collection.

I want to create a generic method which will handle both cases. It should call itself if a collection is passed through. For this I need to check if the type is IEnumerable but the line T is IEnumerable has the following error

TU is a type which is not valid in the given context.

Also, newObject.Select(Map).ToList(); has the following error

TU does not contain a definition for Select

Upvotes: 1

Views: 2030

Answers (1)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29233

The is operator takes an object instance on its left hand side, so it can't be used like that. Instead, you can do this:

if (newObject is IEnumerable) // ...

And because you want to use the instance as a collection later on, you can use the as operator instead:

var newCollection = newObject as IEnumerable<T>;
if (newCollection != null) // ...

Worth pointing out that in cases where all you have is a type (and not an instance), you can achieve the same thing through the IsAssignableFrom method of the Type class, like this:

public static bool IsSequence<T>() => typeof(IEnumerable).IsAssignableFrom(typeof(T));

Upvotes: 2

Related Questions