6

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
}
Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233
  • Use reflection. Does this SO article help? http://stackoverflow.com/questions/1519530/using-reflection-to-find-interfaces-implemented – Ripside Feb 28 '13 at 15:11
  • Would a check of "t as/is IDisposable" do the trick? – RvdK Feb 28 '13 at 15:11
  • @Anthony I don't have an instance of a type, but a type. Can't use `is` on that (I mean I can, but it won't work as expected) – Cristian Diaconescu Feb 28 '13 at 15:12
  • Of course. I deleted my comment as it became more evident you were actually working with the type. – Anthony Pegram Feb 28 '13 at 15:13
  • @RvdK Same comment as for Anthony. I don't work on an instance of some type, but on a `Type` – Cristian Diaconescu Feb 28 '13 at 15:16
  • Possible duplicate of [How to determine if a type implements an interface with C# reflection](http://stackoverflow.com/questions/4963160/how-to-determine-if-a-type-implements-an-interface-with-c-sharp-reflection) – user247702 Nov 30 '16 at 09:20

2 Answers2

15

You can use IsAssignableFrom

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

DEMO

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
6

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.

Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233
  • Will this work even if you implemented say `IFoo` which in-turn implements `IDisposable`? – Earlz Feb 28 '13 at 15:21