views:

73

answers:

2

I have an List<Animal> but in that list I have subclasses of Animal such as Mammal. (Yes that is right; it is a school assignment, so don't be specific, just give me some pointers.)

I should persist it with [Serializable] interface and that is no problem, except when I shall read it back again, I have no idea what subclass the data came from when it's time for reviving the information.

So the question is, how do I store that information?

+3  A: 

You don't need to take care of that yourself, since the framework serializes the type as well it knows which instance to create before the content is actually deserialized. Just create a sample and you'll see what happens... ;-)

Lucero
Same thing said a different way - the object knows what type it is; if you need to know, just ask it! :)
GalacticCowboy
Well, I am surprised. Something that works just out of the box...Not anything that you are used to :-)
Gorgen
Gorgen, compared to the early days of programming, there is quite a lot which does work "out of the box" nowadays... ;)
Lucero
It seems like it shows my age, doesn't it... :-)
Gorgen
Kind of, yes. ;) I think it's a generation question. I've been giving my first programming course (in a students-teach-students setup) some 20 years ago (which wasn't actually the early days of programming, but since I'm interested in the topic I educated myself on the topics), and since then quite a lot has changed. Man, that makes me look old I guess...
Lucero
A: 

The is and as keywords will be your friends for this.

It is good to know that the is keyword tries to perform a cast and returns true or false depending on whether or not the cast was successful.

If you want the actual object, and aren't just interested in its type, you are better of using the as keyword and then checking it for null. This will save you the step of having to cast it again once you've determined the type.

iobrien