How to check if a given value is a general list?

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

What is the best way to check if a given object is a list or can be added to a list?

+54
list generics reflection c #
Apr 27 '09 at 16:07
source share
7 answers
 if(value is IList && value.GetType().IsGenericType) { } 
+62
Apr 27 '09 at 16:12
source share

For you guys use 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()) { //... } 
+75
Apr 27 '09 at 16:25
source share
  bool isList = o.GetType().IsGenericType && o.GetType().GetGenericTypeDefinition() == typeof(IList<>)); 
+11
Apr 27 '09 at 16:14
source share
 if(value is IList && value.GetType().GetGenericArguments().Length > 0) { } 
+5
Apr 27 '09 at 16:09
source share
 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(); } 
+4
Apr 27 '09 at 16:25
source share

Probably the best way is to do something like this:

 IList list = value as IList; if (list != null) { // use list in here } 

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

+1
Apr 27 '09 at 16:08
source share

Based on Victor Rodriguez’s answer, we can develop another method for generics. In fact, the original solution can be reduced to only two lines:

 public static bool IsGenericList(this object Value) { var t = Value.GetType(); return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>); } public static bool IsGenericList<T>(this object Value) { var t = Value.GetType(); return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<T>); } 
+1
Jan 17 '17 at 0:53
source share



All Articles