Determine the object (parent?) from an inherited class.

  • Thread starter Thread starter dsandor
  • Start date Start date
D

dsandor

I have a class that is inherited by another class. Let say:

public class vehicle
{
public string color
{
get ...
set ...
}
}

and..

public class truck : vehicle
{
property int wheels
{
get...
set...
}
}

From within the vehicle class I would like to be able to look at properties
in the truck class. Can this be done with reflection? How can I know what
type of object the 'inheriter' is?

Thanks,
David Sandor
 
David,

If the properties are public or protected, then you have access to them
already. If some of the methods or properties are virtual, and you want to
access the base class functionality, you can use the "base" keyword (much
like "this") and make the calls to those methods/properties.

If you want to access private variables, then you can easily use
reflection on the current type to get the private method/field/property
information, but generally this is a bad idea, as the internals of the class
are not guaranteed to not change.

Hope this helps.
 
dsandor said:
I have a class that is inherited by another class. Let say:

public class vehicle
{
public string color
{
get ...
set ...
}
}

and..

public class truck : vehicle
{
property int wheels
{
get...
set...
}
}

From within the vehicle class I would like to be able to look at properties
in the truck class.

You can do that by casting:

Truck t = (Truck) this;
int w = t.Wheels;

etc

It's normally not a good idea though - there are usually better ways of
doing things using polymorphism etc.
How can I know what type of object the 'inheriter' is?

if (this is Truck)
{
....
}

etc - or use GetType()
 
Back
Top