Phil Whittaker
Phil Whittaker

Reputation: 434

Is of generic type

I have a hierarchy interface of IRoot where H is the hierarchy type and N is the node type. I want to work out if an object is of type IRoot, how would I do this...

I have looked as types matching, reflection interfaces and isassignedfrom, all don't work

Upvotes: 1

Views: 117

Answers (2)

siride
siride

Reputation: 209585

One way:

var ifc = obj.GetType().GetInterface(typeof(IRoot<,>).Name);
if(ifc != null) {
    // operate assuming type is IRoot<,>
}

Make sure to read the documentation on GetInterface() and open generic types. This is weird stuff, so it's important to understand what's going on here.

EDIT: you can also use typeof(IRoot<,>).Name in place of "IRoot`2" in order to avoid having to use hard-coded strings. I've updated the above code to do just that.

Upvotes: 3

sunside
sunside

Reputation: 8249

In addition to the siride's answer:

If you can change the definition of IRoot<H, N> so that it is IRoot<H,N> : IRoot, then the following will also work:

object someInstance = new SomeDerivedClass<TFoo, TBar>();
bool isOfRoot = typeof (IRoot).IsInstanceOfType(someInstance);

or even

bool isOfRoot = someInstance is IRoot;

This makes it a bit more type safe as no strings are involved.

Upvotes: 0

Related Questions