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?
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?
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.
if(value is IList && value.GetType().GetGenericArguments().Length > 0)
{
}
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
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())
{
//...
}