Check the type of generic

I have a little problem with checking the type of a generic.

Lets assume you have a list like this:

public class List<T>
{

}

In there you would like to check what type the T is, so you go like this:

private void CheckType()
{
    if (typeof(T) == typeof(CustomItem))
    {

    }
}

Now I am facing the problem with classes that have a common interface and I like to check if generic is the interface so for example:

public interface ICustomItem
{

}

public class CustomItemA : ICustomItem
{

}

public class CustomItemB : ICustomItem
{

}

Now I would like to have the type check work for both classes and just with the interface:

private void CheckType()
{
    if (typeof(T) == typeof(ICustomItem))
    {

    }
}

This obviously fails, since the type isnt ICustomItem, but either CustomItemA, or CustomItemB. Already found a method that gets a Interface but I don't assume thats the right way to do it:

private void CheckType()
{
    if (typeof(T).GetInterface("ICustomItem") != null)
    {

    }
}

Hope you can help me out.

Ps.: No I dont want to create a instance of T and just use the is operator.

Jon Skeet
people
quotationmark

I suspect you're looking for Type.IsAssignableFrom:

if (typeof(ICustomItem).IsAssignableFrom(typeof(T)))

people

See more on this question at Stackoverflow