Chernikov
Chernikov

Reputation: 857

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

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

Upvotes: 7

Views: 1715

Answers (4)

Daniel Bardi
Daniel Bardi

Reputation: 450

You can use is to check:

MyType obj = new MyType();
if (obj is IList)
{
  // obj implements IList
}

Upvotes: 0

Alconja
Alconja

Reputation: 14873

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"
}

Upvotes: 3

Sam Harwell
Sam Harwell

Reputation: 99869

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

Type type = ...;
typeof(IList).IsAssignableFrom(type)

Upvotes: 13

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827276

You can use the Type.GetInterface method.

if (object.GetType().GetInterface("IList") != null)
{
    // object implements IList
}

Upvotes: 7

Related Questions