Changing a type at runtime?

A

AdamM

How can I change an object's type at runtime?

For example, here's what I want to do in psedocode:


object animal;

if (dog)
{
animal=(dog)animal;
}
else
{
animal=(cat)animal;
}

Thanks!
 
D

Dave Fancher

Are you trying to create a new instance of Dog or Cat and assign it to
animal or is animal already set and you're trying to determine its type?
 
A

AdamM

I already have instances of dog or cat, and I want the generic object to
become a reference to either at runtime, then be able to use their methods.
I keep getting the errors that "object animal has no method bark, or has no
method meow" when I try to use the methods.

Problem is I don't know whether I got a dog or cat instance until runtime,
thus I am trying to make use of a generic object to stand in their place, so
my code isn't a million if-then statements trying to determine whether I got
a dog or cat. I'm trying to reuse code better.

Does that make a bit more sense?

Thanks!
 
D

Dave Fancher

Take a look at my blog. I actually just posted an article about this very
subject (coincidentally using animal, cat, and dog).
http://davefancher.blogspot.com/ The article titled "Inheritance,
Polymorphism, and Casting" may be a little more detailed than you're looking
for but it covers exactly what you're trying to do. In particular, I'll
direct your attention to the "IS" keyword.

HTH
 
J

jeff_louie

Adam.... You cannot really change an objects type, but you can create a reference of type dog or cat.
So objects have class and references (reference variables) have type. In pseudocode:

if (referenceV is dog)
safe to do dogReferenceVariable= (dog)referenceV
else if (referenceV is cat)
safe to do catReferenceVariable= (cat)referenceV

Whenever you see a "switch" like this, a light should go off and you should think is there a better way?
So class abstract animal has virtual method Voice
class cat extends from animal and overrides Voice to Meow
class dog extends from animal and overrides Voice to Bark

This way there is no need to know the concrete class at runtime, just do
referenceV.Voice()
which gets a Meow a Bark or even a Hiss :)

Hope that helps,
Jeff
How can I change an object's type at runtime?
For example, here's what I want to do in psedocode:
object animal;
if (dog)
{
animal=(dog)animal;
}
else
{
animal=(cat)animal;
}
Thanks! <


**********************************************************************
Sent via Fuzzy Software @ http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
 

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