Determining if one type inherits from another type

D

DamienS

Hi,

I need to determine if one type is inheritted from another type. I
don't have instances of the objects (and it's undesirable to create
them).

Can someone please point me in the right direction?

Thanks in advance,


Damien
 
M

Marc Gravell

For classes, you can use:

type1.IsSubclassOf(type2)

If you mean interfaces, this i slightly tricker - but IsAssignableFrom
might do the job.

Marc
 
P

Pavel Minaev

For classes, you can use:

type1.IsSubclassOf(type2)

If you mean interfaces, this i slightly tricker - but IsAssignableFrom
might do the job.

Note that IsSubclassOf will return false if type1==type2 (which is
expected, given its name, but may be surprising in a sense that this
behavior is different from the "is" operator).

The most generic way to do this, which will handle the case described
above, as well as interfaces, is indeed Type.IsAssignableFrom.
 
M

Marc Gravell

The most generic way to do this, which will handle the case described
above, as well as interfaces, is indeed Type.IsAssignableFrom.

Granted; of course, it depends a bit on what is *actually* intended by
"if one type is inheritted from another type", and what the OP wants
that to return for "Foo op Foo".

Marc
 
G

G.S.

Note that IsSubclassOf will return false if type1==type2 (which is
expected, given its name, but may be surprising in a sense that this
behavior is different from the "is" operator).

The most generic way to do this, which will handle the case described
above, as well as interfaces, is indeed Type.IsAssignableFrom.

To piggyback on this thread and learn something - can't the same be
accomplished by using "is"?
 
M

Marc Gravell

"is" will only work for an instance (left-hand operand) and a type
(right-hand operand), so it depends on the full scenario. In this case
it sounds like there is no instance, and the type is known only at
runtime, so "is" can't be used. Of course, my interpretation of the
problem might be incorrect...

Marc
 
P

Pavel Minaev

To piggyback on this thread and learn something - can't the same be
accomplished by using  "is"?

It can, if you have a specific value, and know the type you want to
check for in advance. What we were discussing is rather this
situation:

void Foo(Type type1, Type type2) {
// Need to determine of type1 inherits from type2
}
 
D

DamienS

Thanks for that guys. Very helpful.

For the record...
In this case
it sounds like there is no instance, and the type is known only at
runtime, so "is" can't be used.

.... that was correct in this case.

Damien
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top