C# .NET - How to cast parent class to child - Asked By mostafa hamdy on 27-Feb-12 06:11 AM

Hello all
I have some C# project have  2 classes A and B classes, B inherit from A class
I fill in the A class properties and then I  wish to set this vlaues to some object of B type but I failed and I get the following error message "Unable to cast object of type 'Core' to type 'B'" 
the code I wrote is as the following :

public class A
{
 public A()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    int _ID;
    public int ID
    {
      get
      {
        return _ID;
      }
      set { _ID = value; }
   
    }
    string _Name;
    public string Name
    {
      get
      {
        return _Name;
      }
      set { _Name = value; }

    }

}
========================
public class B:A
{
 public B()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    int _age;
    public int Age
    {
      get { return _age; }
      set { _age=value; }
    }
}

 B obj = new B();
      A objAA = new B();
      objAA.ID=12;
      objAA.Name = "ssss";
      objB =(A) objCore;
      objB.Age = 34;


please if any body get what I mean and can help me to cast some object from type A to B please sene me or tell me about somr URL may help me in doing that
Regards
Mostafa
Somesh Yadav replied to mostafa hamdy on 27-Feb-12 06:18 AM

Hi,

   Actually what I expect the compiler to do is to allocate the memory for the child, copy the memory from parent to child and be done with it.

 

You could create a constructor in the Child that accepts a Parent instance and then copies all of the data across.  It would not be casting, but it sounds like what you mentioned above, would that be acceptable.  I would recommend refactoring your code so that you would not need to do this i.e.

using System;

using System.Collections.Generic;

using System.Text;

 

namespace ConsoleApplication10

{

    class Program

    {

      static void Main(string[] args)

      {

        Parent p = new Parent("Bob");

        Child c = new Child(p, "Drum");

      }

    }

 

    class Parent

    {

      string name;

 

      public Parent(string name)

      {

        this.name = name;

      }

 

      public string Name

      {

        get

        {

          return this.name;

        }

      }

    }

 

    class Child : Parent

    {

      string favouriteToy;

 

      public Child(Parent parent, string favouriteToy) : base(parent.Name)

      {

        this.favouriteToy = "None";

      }

    }

}


Web Star replied to mostafa hamdy on 27-Feb-12 06:18 AM
Check this if you instantiated the object of both class as follows
Base derivedInstance = new Derived();
Base baseInstance = new Base();

and try to cast the object

Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws Invalid Cast Exception

it you need to first create your child class object on base class than such type of casting will be work
kalpana aparnathi replied to mostafa hamdy on 27-Feb-12 06:19 AM
hi,

In the code, by inherting from parent, you're saying "Child is a kind of Parent". Okay, sounds weird due to the names, but perfectly acceptable. Then with the "child c = (child)p" cast, you are, in essence, telling the compiler that "Parent is a kind of Child". It's not. The inference is backwards.

As previously stated, I would re-work the class diagram if you need something like this to work. It sounds like some sort of mistake was made in the inheritance architecture somewhere. If all you need is for both child and parent to implement common methods so that when either of the objects is passed to some function it can operate on some common methods on the passed-in object (holy polymorphism, Batman!), then just have the two of them implement the same interface, or type the function parameter as the base class and make sure the methods exist on the base class.


Regards,