Cristian Diaconescu
Cristian Diaconescu

Reputation: 35641

C# How to determine if a type implements a given interface?

I want the following to return true:

var isIt = IsDisposable(typeof(TextWriter));

where:

bool IsIDisposable(Type t){
    ??? 
    // I tried:
    //return t.IsSubclassOf(typeof(IDisposable)); //returns false
    // the other t.IsXXX methods don't fit the requirement as far as I can tell
}

Upvotes: 6

Views: 11879

Answers (2)

Cristian Diaconescu
Cristian Diaconescu

Reputation: 35641

I found it: Type.GetInterfaces() is what I need:

bool IsIDisposable(Type t){
    return t.GetInterfaces().Contains(typeof(IDisposable));
}

From the documentation, Type.GetInterfaces() returns:

Type: System.Type[]
An array of Type objects representing all the interfaces implemented or inherited by the current Type.

Upvotes: 6

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use IsAssignableFrom

bool IsDisposable = typeof(IDisposable).IsAssignableFrom(typeof(TextWriter));

DEMO

Upvotes: 16

Related Questions