Rand Random
Rand Random

Reputation: 7440

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.

Upvotes: 1

Views: 128

Answers (2)

TypeIA
TypeIA

Reputation: 17250

Best bet is IsAssignableFrom()...

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

You can also do this, which is basically the same as what you found except without the string comparison...

if (typeof(T).GetInterfaces().Contains(typeof(ICustomItem))) { }

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

I suspect you're looking for Type.IsAssignableFrom:

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

Upvotes: 4

Related Questions