views:

688

answers:

7
public bool IsList(object value)
    {
        Type type = value.GetType();
        // Check if type is a generic list of any type
    }

What's the best way to check if the given object is a list, or can be cast to a list?

+2  A: 

Probably the best way would be to do something like this:

IList list = value as IList;

if (list != null)
{
    // use list in here
}

This will give you maximum flexibility and also allow you to work with many different types that implement the IList interface.

Andrew Hare
this does not check if it a *generic* list as asked.
Lucas
+4  A: 
if(value is IList && value.GetType().GetGenericArguments().Length > 0)
{

}
BFree
I think you need a call to GetType() e.g. value.GetType().GetGenericArguments().Length > 0
ScottS
Oops, you're right. My mistake.
BFree
+10  A: 
if(value is IList && value.GetType().IsGenericType) {

}
James Couvares
This does not work - I get the following exception - value is IList Using the generic type 'System.Collections.Generic.IList<T>' requires '1' type arguments
You need to add using System.Collections; on top of your source file. The IList interface I suggested is NOT the generic version (hence the second check)
James Couvares
You're right. This works like a charm. I was testing this in my Watch window and forgot all about the missing namespace. I like this solution better, very simple
+1  A: 
 bool isList = o.GetType().IsGenericType 
                && o.GetType().GetGenericTypeDefinition() == typeof(IList<>));
Eoin Campbell
+1  A: 
public bool IsList(object value) {
    return value is IList 
        || IsGenericList(value);
}

public bool IsGenericList(object value) {
    var type = value.GetType();
    return type.IsGenericType
        && typeof(List<>) == type.GetGenericTypeDefinition();
}
Atif Aziz
+2  A: 

For you guys that enjoy the use of extension methods:

public static bool IsGenericList(this object o)
{
    bool isGenericList = false;

    var oType = o.GetType();

    if (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>)))
     isGenericList = true;

    return isGenericList;
}

So, we could do:

if(o.IsGenericList())
{
 //...
}
Victor Rodrigues