Reputation: 1933
I want to check if a generic variable is of a certain type but don't want to check the generic part.
Let's say I have a variable of List<int>
and another of List<double>
. I just want to check if it is of type List<>
if(variable is List) {}
And not
if (variable is List<int> || variable is List<double>) {}
is this possible?
Thanks
Upvotes: 3
Views: 1084
Reputation: 1062780
You can test an exact type via reflection:
object list = new List<int>();
Type type = list.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
Console.WriteLine("is a List-of-" + type.GetGenericArguments()[0].Name);
}
Personally, though, I'd look for IList<T>
- more versatile than the concrete List<T>
:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Console.WriteLine("Is an IList-of-" +
interfaceType.GetGenericArguments()[0].Name);
}
}
Upvotes: 6
Reputation: 421988
variable.GetType().IsGenericType &&
variable.GetType().GetGenericTypeDefinition() == typeof(List<>)
Of course, this only works if variable is of type List<T>
, and isn't a derived class. If you want to check if it's List<T>
or inherited from it, you should traverse the inheritance hierarchy and check the above statement for each base class:
static bool IsList(object obj)
{
Type t = obj.GetType();
do {
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
return true;
t = t.BaseType;
} while (t != null);
return false;
}
Upvotes: 9
Reputation: 269368
Type t = variable.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
{
// do something
}
Upvotes: 5