2

I've got an interesting issue with type comparison. I'm attempting to compare an implied type with an explicit type, to test if something is any sort of collection

var obField = value.GetType().InvokeMember(_stCollectionField, 
                              System.Reflection.BindingFlags.GetProperty, 
                              null, value, null);

if (obField.GetType() != typeof(IEnumerable<object>))
{
    return true;
}

During my testing, I can ensure that obField will turn out to be a collection of objects. However, I'm finding that it will always run inside the check and return true, where instead I wish it to skip past that (becasue the two types are equal.)

A little debugging gives me the type of obField as object {System.Collections.Generic.List<System.DateTime>}.

How can I go about matching that type?

Thanks

Andy Hunt
  • 1,053
  • 1
  • 11
  • 26

1 Answers1

3

Use Type.IsAssignableFrom, as used here: Getting all types that implement an interface

For example:

if (typeof(IEnumerable<object>).IsAssignableFrom(obField.GetType())) { ... }
Community
  • 1
  • 1
George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • 1
    Addition: This will only work in .NET 4, because covariance for interfaces wasn't available earlier. – Daniel Hilgarth Jul 06 '11 at 11:52
  • @Andy: If you want to test for any sort of collection then you'd probably be better off comparing against the non-generic `IEnumerable` interface. – LukeH Jul 06 '11 at 13:13