On Fri, 29 Jun 2007 14:16:54 -0700, Bob Jones <go********@gmail.comwrote:
[...]
I can implicitly convert to ClassA from ClassB and ClassC. Easy enough
I would like to convert ClassB to ClassA and then create a new
instance of ClassC and use the converted ClassA to fill in the derived
methods and properties in ClassC without having to write code that
literally copies values from one class to the other. Is this possible?
No.
And you should keep in mind that when you cast from ClassC to ClassA (for
example), you are _not_ "converting" anything. You are simply changing
the view onto the instance. The instance remains a ClassC instance, and
in fact will behave exactly like a ClassC instance with respect to any
members in ClassA that ClassC overrides.
You can, of course, write constructors for ClassB and ClassC that take a
ClassA for initialization, and then copy the data from a ClassA-derived
instance to help initialize the new instance of ClassB or ClassC. But you
probably already knew that.
And if the point in my first paragraph wasn't clear enough:
Psuedo Code:
ClassB classb = new ClassB();
ClassC classc = new ClassC();
ClassB classb2 = (ClassB)(ClassA)classc; //this doesn't work but you
get the point.
What you get from the "(ClassA)classc" part of that line of code is still
a ClassC instance. You've changed how it looks, essentially "stripping
off" what the _compiler_ knows about it being a ClassC. But the instance
itself still knows it's a ClassC (for example, if you called the GetType()
method on the instance, it'd still tell you ClassC). So, just as you
can't cast a ClassC to a ClassB when the variable is typed as ClassC, you
also can't cast a ClassC to a ClassB just because the variable is typed as
a ClassA.
For that matter, you can't even cast a ClassA to a ClassB, if it's really
just a ClassA. The only way to validly cast something to a ClassB is if
it is either a ClassB, or something that derives _from_ ClassB.
Pete