Checking type parameter of a generic method in C#

Yes:

if (typeof(T) == typeof(MyClass))
{
    MyClass mc = (MyClass)(object) t;
}
else if (typeof(T) == typeof(List<MyClass>))
{
    List<MyClass> lmc = (List<MyClass>)(object) t;
}

It’s slightly odd that you need to go via a cast to object, but that’s just the way that generics work – there aren’t as many conversions from a generic type as you might expect.

Of course another alternative is to use the normal execution time check:

MyClass mc = t as MyClass;
if (mc != null)
{
    // ...
}
else
{
    List<MyClass> lmc = t as List<MyClass>;
    if (lmc != null)
    {
        // ...
    }
}

That will behave differently to the first code block if t is null, of course.

I would try to avoid this kind of code where possible, however – it can be necessary sometimes, but the idea of generic methods is to be able to write generic code which works the same way for any type.

Leave a Comment