Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast child object as parent

Tags:

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.

like image 389
Jules Avatar asked Jan 31 '12 15:01

Jules


People also ask

Can we typecast child to parent?

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.

Can parent reference hold child object?

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.

Can we assign child object to parent objects 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.)

Can we typecast parent to child in C#?

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).


1 Answers

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?

like image 95
Matt Grande Avatar answered Sep 27 '22 19:09

Matt Grande