Query for ancestor

  • Thread starter Thread starter Jesper
  • Start date Start date
J

Jesper

Hi,

Is it possible to query an object for an ancestor. I.e.
determine if an object is derived from a certain type of
class.

thanx.

Jespr.
 
MyBaseObject mbo = new MyBaseObject();
MyInheritedObject mio = new MyInheritedObject();

bool isDescendant = mbo.GetType().IsInstanceTypeOf(mio);

If you know the ancestor type in advance, it'll work for
you. I can't think of the other method off of the top of
my head, but I'm pretty sure I remember a post by Rockford
Lhotka in the wrox groups about figuring out the ancestor
of an object...I'll see if I can find it.

Good Luck,

Bill

W.G. Ryan
(e-mail address removed)
www.knowdotnet.com
 
if you know the type you wish to check, for example
System.ComponentModel.Component, you can simiply do:
object o = <getobject>;
if (o is System.ComponentModel.Compnent) {
//do whatever,
}

otherwise
object o = <getobject>;
object c = <getdifferntObject>;
if (o.GetType().IsSubClassOf(c.GetType())) {
//do whatever
}

note, that in C#, the typeof() keyword can be used instead of the .GetType()
method.
 
Back
Top