Tuesday, May 3, 2011

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

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?

From stackoverflow
  • 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.

    Lucas : this does not check if it a *generic* list as asked.
  • if(value is IList && value.GetType().GetGenericArguments().Length > 0)
    {
    
    }
    
    ScottS : I think you need a call to GetType() e.g. value.GetType().GetGenericArguments().Length > 0
    BFree : Oops, you're right. My mistake.
  • Maybe you find answer here http://stackoverflow.com/questions/755200/how-do-i-detect-that-an-object-is-a-generic-collection-and-what-types-it-contain

  • if(value is IList && value.GetType().IsGenericType) {
    
    }
    
    James Couvares : 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)
  •  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();
    }
    
  • 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())
    {
     //...
    }
    

0 comments:

Post a Comment