"Daniel" <Da*****@vestryonline.comwrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
Ok i understand now.
What i dont get is this.
GenericAnimal g = (GenericAnimal)Dog;
yet if you look at g's type it remains Dog?? Why has it not become a
generic type?
Did you read the other thread I pointed you to?
The instance doesn't change type. Only the type of the reference *to* that
instance has changed. Casting it to GenericAnimal doesn't change the
instance...it just restricts your view of the instance to those things
within a GenericAnimal.
Sometimes I wonder if teaching people OOP with C# is such a great idea.
Ironically, because things are more abstracted in comparison to C++, the
difference between an object and a reference to that object are lost. I
suspect that if people had to distinguish between an instance and a pointer
to that instance (as they do in C++), these questions wouldn't come up
nearly as often as they do.
Anyway, back to the question: "g" is not the instance. It's a reference to
the instance. Likewise, "Dog" is not the instance, it's a reference to the
instance (that is, let's ignore that you made the same error you made
previously, using the name of a class rather than the name of an instance of
that class :) ). The type of the reference affects what of the instance you
can look at, but it doesn't change the instance itself. When you create a
new Dog, you are creating an instance. The variables that reference that
instance define the type used to view the instance, but not the type of the
instance itself.
Thus, the instance always keeps its original type. You can always cast
references to that type back and forth, as long as they remain consistent
with the type of the actual instance. IMHO, it's a mistake to think of
casting as being "up-cast" or "down-cast". In all cases, the casting is
just providing a new type through which to view the instance. The type cast
to must always be a type within the inheritance tree of the instance, and
will always either be the type of the instance itself, or an ancestor of
that instance's type (that is, a base class). But no matter what happens,
the validity of the cast is relative to the original instance, not the type
being cast from.
Pete