Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that type is inherited from some interface c#

I have following:

Assembly asm = Assembly.GetAssembly(this.GetType());  foreach (Type type in asm.GetTypes()) {     MyAttribute attr = Attribute.GetCustomAttribute(type, typeof(MyAttribute))    as MyAttribute;      if(attr != null && [type is inherited from Iinterface])      {         ...      }  } 

How can i check that type is inherited from MyInterface? Does is keywork will work in this way?

Thank you.

like image 911
iburlakov Avatar asked Dec 02 '10 11:12

iburlakov


People also ask

CAN interfaces inherit interfaces?

Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.

What type is an interface C#?

Some of the interface types in C# include. IEnumerable − Base interface for all generic collections. IList − A generic interface implemented by the arrays and the list type. IDictionary − A dictionary collection.

CAN interfaces inherit from each other?

But unlike classes, interfaces can actually inherit from multiple interfaces. This is done by listing the names of all interfaces to inherit from, separated by comma. A class implementing an interface which inherits from multiple interfaces must implement all methods from the interface and its parent interfaces.

Can you inherit an interface C#?

C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.


2 Answers

No, is only works for checking the type of an object, not for a given Type. You want Type.IsAssignableFrom:

if (attr != null && typeof(IInterface).IsAssignableFrom(type)) 

Note the order here. I find that I almost always use typeof(...) as the target of the call. Basically for it to return true, the target has to be the "parent" type and the argument has to be the "child" type.

like image 159
Jon Skeet Avatar answered Sep 25 '22 09:09

Jon Skeet


Check out IsAssignableFrom http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

like image 29
CRice Avatar answered Sep 26 '22 09:09

CRice