-5

Let's suppose this 2 classes:

public class ParentClass
{
    public String field1;
    public String field2;
}

public class ChildClass : ParentClass
{
    public String field3;
}

Now, i am instantiating an object:

   var c1 = new ParentClass();
   c1.field1 = "aaa";
   c1.field2 = "bbb";

You can imagine this object is provided by an external function or another object. So i cannot change his type. This is a ParentClass object. I cannot change his type in the external function.

What i want to do now is to "attach" a field3 information on this object:

   var c2 = c1 as ChildClass;     // c2 is null !
   c2.field3 = "ccc";

I do not understand why, but c2 is null. ChildClass is derivated from ParentClass so i do not understand why cast is not valid. How can i do ?

Thanks a lot

Bob5421
  • 7,757
  • 14
  • 81
  • 175
  • You can't. Inheritance defines an `is a` relation. A parent isn't a Child. If what you wanted was possible, what would be the value of `field3`? `c1` has no such property or field – Panagiotis Kanavos Oct 05 '21 at 13:32
  • I think this post answers your question: https://stackoverflow.com/questions/988658/unable-to-cast-from-parent-class-to-child-class – Artur Gasparyan Oct 05 '21 at 13:33
  • `c1` is NOT a `ChildClass` and therefore cannot be cast to it. – Matthew Watson Oct 05 '21 at 13:33
  • Casts do two different types of things - one changes *what the compiler knows about the type*, based on a programmer's assertion that they know better than the compiler what the type really is. This type of cast doesn't *change* the type of the object, and is the type involved when casting within a type hierarchy. The other type of cast *changes the type of the object*, using built-in or user-defined conversion operators. But those *aren't even allowed* within a type hierarchy where the first type of cast could happen. – Damien_The_Unbeliever Oct 05 '21 at 13:46

1 Answers1

1

A parent is not a child, hence this cast is impossible. To understand this, biological terms are often the best: There is a class Animal and two classes Fox and Deer whic hinherit Animal. You cannot cast an Animal to Fox, because it might be a Deer.

If you want to do this, I recommend that you add a constructor to child which copies field1 and field2 from a parent:

public class ChildClass : ParentClass
{
    public ChildClass(ParentClass parent)
    {
       field1 = parent.field1;
       field2 = parent.field2;
    }

    public String field3;
}

You can call it like that:

var c2 = new ChildClass(c1);     
c2.field3 = "ccc";
SomeBody
  • 7,515
  • 2
  • 17
  • 33