Home > Enterprise >  Cast a C# Class to his child class [duplicate]
Cast a C# Class to his child class [duplicate]

Time:10-05

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

CodePudding user response:

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";
  • Related