Inheritance question

  • Thread starter Thread starter hello_world
  • Start date Start date
H

hello_world

Let's say I have the following class hierarchy:

A: B
B: C

I would like a means to test whether class C is a 'descendant' of class
A (or A is the 'ancestor' of C). If c is the instance of C,
c.GetType().BaseType only gives me type that is directly inherited, and
i need to get the type(s) beyond that. Thanks!
 
hello_world said:
Let's say I have the following class hierarchy:

A: B
B: C

I would like a means to test whether class C is a 'descendant' of class
A (or A is the 'ancestor' of C). If c is the instance of C,
c.GetType().BaseType only gives me type that is directly inherited, and
i need to get the type(s) beyond that. Thanks!

Well, you can use BaseType on the the type returned by
GetType().BaseType of course:

Type x = c.GetType().BaseType.BaseType

You might want to look at the "is" and "as" operators though for most
of the problems you'll run across when you want to know this kind of
thing.

Jon
 
In fact my example is wrong, as you might have guessed :P It should
have been:

B: A
C: B

Thanks again, i'll use the IsSubclass method - it will surely do the
trick!
 
hello_world said:
In fact my example is wrong, as you might have guessed :P It should
have been:

B: A
C: B

Thanks again, i'll use the IsSubclass method - it will surely do the
trick!

Unless you've actually got the *types*, using "is" or "as" will be a
lot faster, and more obvious in terms of meaning too:

if (c is A)

or

A x = c as A;
if (x != null)
{
// Work with x here
}

Jon
 
Thanks Jon, i'll give it a try - it seems less expensive in terms of
calls to methods.
 
You can just use "is".

if (c is A)

Or, if you really want, you can keep digging down the descendent chain:

c.GetType().BaseType.BaseType...
 

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

Back
Top