0

Ok, this may sound odd, but I need to test if an object passed to me is of type ModelItem<T> where I don't care what T actually is. In other words, if it's a ModelItem<int>, ModelItem<string> or ModelItem<Foo>, then I need to return true.

Note: If I were the owner of ModelItem<T>, I would think to just define an interface of type IModelItem and assign it as part of the ModelItem<T> definition, but I don't have access to the source.

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286

1 Answers1

3

Sure, it's possible:

public bool IsIt(object thing)
{
    var type = thing.GetType();
    if (type.IsGenericType)
    {
        return type.GetGenericTypeDefinition() == typeof(MyThing<>);
    } 
    return false;
}

Testing it:

IsIt(new MyThing<int>()).Dump();
IsIt(new MyThing<string>()).Dump();
IsIt(new MyThing<Foo>()).Dump();
IsIt(5).Dump();

Returns

True
True
True
False
Rob
  • 26,989
  • 16
  • 82
  • 98