Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a given value is a generic list?

People also ask

How do I know the generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

Can lists be generic?

You can't declare a list of generic types without knowing the generic type at compile time. You can declare a List<Field<int>> or a List<Field<double>> , but there is no other common base type for Field<int> and Field<double> than object .


For you guys that enjoy the use of extension methods:

public static bool IsGenericList(this object o)
{
    var oType = o.GetType();
    return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>)));
}

So, we could do:

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

using System.Collections;

if(value is IList && value.GetType().IsGenericType) {

}

 bool isList = o.GetType().IsGenericType 
                && o.GetType().GetGenericTypeDefinition() == typeof(IList<>));

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();
}