Search code examples
c#type-conversionimplicit-typing

Implicit type comparison with explicit type - C#


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


Solution

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

    For example:

    if (typeof(IEnumerable<object>).IsAssignableFrom(obField.GetType())) { ... }