Collection of Derived Objects

J

John Comber

Hi

I'd like to create a collection of objects (Employee, Part-time
employee, etc.) where these objects are derived from a base class
(Person).

As I understand it, I have to create a collection with type Person so
that each dervied object can be stored in the same collection.

However, when itterating through the objects in the collection, is
there a way to determine the original type of each object so that I can
cast back to that type to use the properties and method of the derived
objects?

Many TIA
John.
 
K

Kalpesh

You can use typeof operator to determine the type of the object & do
your operations then

eg (pseudocode)
If obj.getttype().tostring() == "PartTime"
{
....
}
elseif obj.getttype().tostring() == "Employee"
{
.....
}

Does this help ?

Kalpesh
 
P

Phill. W

John Comber said:
As I understand it, I have to create a collection with type Person so
that each dervied object can be stored in the same collection.

However, when itterating through the objects in the collection, is
there a way to determine the original type of each object so that I can
cast back to that type to use the properties and method of the derived
objects?

Ask each Object what it is, and deal with it based on that, as in

For Each who As Person In (collection)
If TypeOf who Is PartTime Then
DirectCast( who, PartTime ).method1()
ElseIf Typeof who is FullTime Then
DirectCast( who, FullTime ).method2()
End if
Next

HTH,
Phill W.
 

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