I need to be able to cast an instance of a child object to an instance of its parent object.
public class Parent { public string name{ get; set; } } public class Child : Parent { } var myClass = new Child(); (Parent)myClass;
The cast above doesn't seem to work, and the object still has child's type when serialized.
Is there another way to cast it?
I'm only using the child class for validation– I need the child to have only the parent's type for serialization reasons.
Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child's properties. However, we can forcefully cast a parent to a child which is known as downcasting.
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
In real world, parents can accommodate children but children cannot accommodate parents. same is the case in OOP. class Parent { int prop1; int prop2; } class Child : Parent // class Child extends Parent (in case of Java Lang.)
Parent to Child (Explicit casting - Can be successful) Note: Because objects has polymorphic nature, it is possible for a variable of a parent class type to hold a child type. Conclusion : After reading above all, hope it will make sense now like how parent to child conversion is possible(Case 3).
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With