How to check that the current type (type object) has the necessary interface (or parent type)

I have some type ( Type object). You must verify that this type has an IList interface.
How can i do this?

+7
c # types
source share
4 answers

Assuming you have a type object with type System.Type (which I compiled from OP),

 Type type = ...; typeof(IList).IsAssignableFrom(type) 
+13
source share

You can use the Type.GetInterface method.

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

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" } 
+3
source share

You can use is to check:

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

All Articles