Forum Moderators: open

Message Too Old, No Replies

Store and retrieve inherited objects in an ArrayList

A common problem, maybe there's a suitable design pattern out there?

         

bhonda

2:35 pm on Mar 6, 2008 (gmt 0)

10+ Year Member



Hey guys,

I've got a real quick question. I hope this is the right section for this.

Here's my situation. I have an application, written in C#. In this application, I have a class. Say, ParentClass. I have a number of other classes that each inherit from ParentClass, say ChildClassA, ChildClassB and ChildClassC.

I need to create an array of these objects, so I use ArrayList<ParentClass>. This allows me to add ChildClassA, ChildClassB and ChildClassC to the same array.

This is good.

However, my problem is using the objects once they've been put into the array.

I can get an object out, at say, index 2. This will give me an instance of ParentClass. But how do I know whether it was originally of type ChildClassA, ChildClassB or ChildClassC?

This may be a really simple question...and I'm sure I should already know this by now, but all the solutions I've hacked together all seem a little messy.

My question: Is there a real easy way to cast these objects back to their original classes, or do I have to do it manually, in something like a huge Switch statement?

I hope that makes sense. Let me know if not!

Cheers in advance,

B

Lord Majestic

3:01 pm on Mar 6, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can use C# construct:

if(oObject is ChildClassA)
{
// some stuff here
}