tags:

views:

155

answers:

3

Hi all,

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

+7  A: 
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;
}
Mehrdad Afshari
GetGenericTypeDefinition() is a bit more natural than MakeGenericType() without arguments.
@weiqure: Ooooops. Right. It was actually wrong. Fixed.
Mehrdad Afshari
Yeah. The complete code is the second one. The first line just focuses on the idea.
Mehrdad Afshari
thanks for the quick reply. this works perfectly!
Tarscher
+4  A: 
Type t = variable.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
{
    // do something
}
LukeH
+3  A: 

You can test an exact type via reflection:

object list = new List();

    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);
        }
    }
Marc Gravell