1

For starters, this question is not a repeat of this post that I have read 100 times (please read on for question): How to determine if a type implements an interface with C# reflection

I'm using reflection to iterate through properties on objects dynamically at runtime to manipulate and add data. The root issue for me is naturally, you cannot instantiate an instance of an Interface and therefore my code using Activator.CreateInstance later downstream must not be ran against types found to be an Interface or a collection of an Interface type.

Say I have the following on an Person class:

public IList<Address> addresses1 {get ; set; } \\ This property **should** flag being an Interface public List<Address> addresses2 {get ; set; } \\ This property **should NOT** flag being an Interface

Using the following code while reflecting on the property I can find out if the property implements an Interface:

propertyTypeFromReflection.GetInterfaces().Any()

The problem I have is both IList<Address> and List<Address> have the statement above return true. That's because even List<T> as we know actually implements a slew of Interfaces (i.e. IList, ICollection, IEnumerable, etc.).

Since I am doing this investigation dynamically, I have no idea of how to test if my type implements a specific Interface like all the examples show such as the link I posted at the beginning which do the following:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType)) typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

I need help determining if the object Property reflected upon dynamically and in focus, is directly an Interface as opposed to a concrete type? All the examples require testing the known Interface to a known concrete type, but since this is happening dynamically I don't know how to accomplish this?

3
  • 4
    Type.IsInterface property? May 26, 2015 at 21:48
  • 2
    Did you read the documentation?
    – SLaks
    May 26, 2015 at 21:49
  • 1
    @SLaks - Appreciate your quality assistance. It certainly helped me resolve this issue.
    – atconway
    May 26, 2015 at 21:58

1 Answer 1

4

You can use Type.IsInterface Property https://msdn.microsoft.com/en-us/library/system.type.isinterface(v=vs.110).aspx

1
  • Case of can't see the forest through the trees - this worked perfectly. In my very working man's knowledge of C# reflection I obviously missed this.
    – atconway
    May 26, 2015 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.