cast child object as parent
You're not assigning the cast to anything.
var myClass = new Child();
Parent p = (Parent)myClass;
Edit - I think you misunderstand how casting works. Say Parent has a virtual
method, DoStuff()
that is overridden in Child
. Even if you cast myClass
to Parent
, it's going to run the Child
's DoStuff
method. No matter what, that Child
is a Child
, and will always be a Child
, even if you cast it.
If you're trying to pass it to a method that accepts a Parent
object, you don't have to cast it. It's already a Parent
, by virtue of being a Child
.
I think we're missing something. What are you trying to accoplish? What's not working?
That should work.
But I suspect from the way you've written your code that you haven't captured the cast object in a new variable? Try this:
var myClass = new Child()
var myClassAsParent = (Parent)myClass;
// myClassAsParent still has the type "Child", but can be accessed as if it were a Parent.
Edit
Based on some of the comments you've been leaving, I believe you misunderstand a fundamental aspect of most programming languages. It is this: the Type of an object cannot change. An object that was instantiated as a Child
object will always be a Child
object.
Casting does not change the type of an object. Casting changes the way the rest of the program "sees" the object. It changes the interface of the object, if you will. So if you cast a Child
object to a Parent
type, the rest of the program thinks it's dealing with a Parent
type, but it's really dealing with a Child
type that is, to use a really bad analogy, dressed up in its parent's clothing.
In short, Casting doesn't do what you think it does.
problem is the xml serialiser serialises the object with child type as root element. i dont really want to pass my target type all the way down into the serialiser. is there a better way? – Jules
I haven't worked with serialization much, but my guess is that you're going to need to alter your definition of "how do I serialize myself" in the child element to write itself out as if it was a parent.
If you want to actually have and instance of "Parent" then you'll need to create a new Parent and copy all of the values from the Child to that Parent. (I wouldn't do this if you have a lot of them, but if you don't have that many then it shouldn't be a problem.) The easiest way to do this would be to make a copy constructor in Parent. It would be a constructor that take a Parent as a parameter and copies the values (Name in this case, and I assume you may have omitted others) from the parameter to itself. You can then make a new Parent, pass in the Child as the parameter (since a Child is a Parent, no cast/conversion is needed) and it will spit out an actual instance of Parent.