Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that current type (object of Type) has needed interface (or parent type)

Tags:

c#

.net

types

I've a some type (object of Type). Need to check that this type has interface IList.
How I can do this?

like image 759
Chernikov Avatar asked Aug 04 '09 07:08

Chernikov


3 Answers

Assuming you have an object type with the type System.Type (what I gathered from the OP),

Type type = ...;
typeof(IList).IsAssignableFrom(type)
like image 176
Sam Harwell Avatar answered Oct 22 '22 01:10

Sam Harwell


You can use the Type.GetInterface method.

if (object.GetType().GetInterface("IList") != null)
{
    // object implements IList
}
like image 31
Christian C. Salvadó Avatar answered Oct 22 '22 00:10

Christian C. Salvadó


I think the easiest way is to use IsAssignableFrom.

So from your example:

Type customListType = new YourCustomListType().GetType();

if (typeof(IList).IsAssignableFrom(customListType))
{
    //Will be true if "YourCustomListType : IList"
}
like image 3
Alconja Avatar answered Oct 21 '22 23:10

Alconja