24

I have the following case:

public interface IPerson { .. }    
public class Person : IPerson { .. }    
public class User : Person { .. }

Now; if I have a "User" object - how can I check if this implements IPerson using reflection? To be more precise I have an object that might have a property SomeUser, which should be of some type implementing the interface "IPerson". In my case I actually have a User, but this is what I want to check through reflection. I can't figure out how to check the property type since it is a "User", but I want to check if it implements IPerson...:

var control = _container.Resolve(objType); // objType is User here
var prop = viewType.GetProperty("SomeUser");
if ((prop != null) && (prop.PropertyType is IPerson)) 
{ .. }

(Note that this is a simplification of my actual case, but the point should be the same...)

stiank81
  • 25,418
  • 43
  • 131
  • 202
  • 5
    If you already have an object instance you do not need reflection to check whether your object implements a certain interface. You can simply check `if (objUser is IPerson)` – Dirk Vollmar Oct 05 '09 at 12:14
  • Isn't 0xA3's comment the correct answer? – itchi Nov 22 '11 at 21:41

3 Answers3

33

Check the Type.IsAssignableFrom method.

Konamiman
  • 49,681
  • 17
  • 108
  • 138
20
var control = _container.Resolve(objType); 
var prop = viewType.GetProperty("SomeUser");
if ((prop != null) && (prop.PropertyType.GetInterfaces().Contains(typeof(IPerson))) 
{ .. }
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • Thanks, but think I'll go with Type.IsAssignableFrom. – stiank81 Oct 05 '09 at 11:59
  • Type.IsAssignableFrom actually came back false in a LINQ expression where it should have been true. This Type.GetInterfaces().Contains([Interface Type]) worked. – Juls Jun 23 '21 at 15:18
0

See Implementations of interface through Reflection.

Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184