locked
trying to convert Parent class object to Child class object

    Question

  • I am trying to cast a parent class object to a child class object.  I get a runtime error of InvalidCastException was unhandled.  Unable to cast object of type 'S_XREF_Entities.Source_Element' to type 'S_XREF_Entities.Assembler_Program_Source_Element'.

    I then tried to do an explicit conversion and was told by the compiler that

     #region implicit operators
            public static explicit operator Assembler_Program_Source_Element(Source_Element MySourceElement)
            {
                Assembler_Program_Source_Element MyAssemblerProgramSourceElement = new Assembler_Program_Source_Element();
                MyAssemblerProgramSourceElement.Element_Location = MySourceElement.Element_Location;
                MyAssemblerProgramSourceElement.Element_Name = MySourceElement.Element_Name;
                MyAssemblerProgramSourceElement.Element_Type = MySourceElement.Element_Type;
                MyAssemblerProgramSourceElement.Element_Version = MySourceElement.Element_Version;
                MyAssemblerProgramSourceElement.File_Commands = MySourceElement.File_Commands;
                MyAssemblerProgramSourceElement.File_Lines = MySourceElement.File_Lines;
     
    Error 1 'S_XREF_Entities.Source_Element.explicit operator S_XREF_Entities.Assembler_Program_Source_Element(S_XREF_Entities.Source_Element)': user-defined conversions to or from a derived class are not allowed C:\Documents and Settings\n097377\My Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Source_Element.cs 203 23 SharesSourceCodeCrossRefference
                return MyAssemblerProgramSourceElement;         }
    any ideas??

    Peter G. Simmon
    Friday, August 19, 2011 5:37 PM

Answers

  • I would add a constructor to the derived/child class that accepted an instance of a base class object.  The code you have posted looks like it would make for good content. 

    Assembler_Program_Source_Element MyAssemblerProgramSourceElement = new Assembler_Program_Source_Element();
          MyAssemblerProgramSourceElement.Element_Location = MySourceElement.Element_Location;
          MyAssemblerProgramSourceElement.Element_Name = MySourceElement.Element_Name;
          MyAssemblerProgramSourceElement.Element_Type = MySourceElement.Element_Type;
          MyAssemblerProgramSourceElement.Element_Version = MySourceElement.Element_Version;
          MyAssemblerProgramSourceElement.File_Commands = MySourceElement.File_Commands;


    The constructor could be private or public, and your static method could simply call the constructor to obtain a new instance.

     

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/


    • Marked as answer by PeterSimmon Friday, August 19, 2011 8:39 PM
    Friday, August 19, 2011 7:46 PM
    Moderator

All replies

  • You cannot cast a base class object to a derived class.  But you can cast a derived class to a base class because a derived instance "contains a" base class instance.  Here's some test code to clearly illustrates this concept.  Set a breakpoint where indicated, and step through the code until the next line in the static method is hit.

      class BaseClass
      {
        protected int num1 = 1; // make it accessible by derived classes
    
        public BaseClass()
        {
          this.num1 = 2;
          return; // gives Debugger something to do to show you
        }
      }
    
      class DerivedClass : BaseClass
      {
        protected int num2 = 1;
    
        public DerivedClass()
        {
          this.num2 = 2;
          this.num1 = 3; // 'num1' was set 3 different times
          return; // gives Debugger something to do to show you
        }
      }
    
      class DemoClass
      {
        public static void BaseClassDemo()
        {
          BaseClass bc = new BaseClass(); // set breakpoint here
          DerivedClass dc = new DerivedClass(); 
          return;
        }
      }


    Did you see a base class object get constructed for the "bc" variable?  Did you see a base class object get constructed for the "dc" variable prior to the derived class object being constructed? 

    When you cast objects from derived to base, that instance "contained" within the derived class you saw constructed is what is accessed or "filtered" out of the object graph in memory.  But, when you saw the base class get constructed by itself, there was no construction of a derived instance.  The extra stuff added by the derived class does not exist with a base class object instance, which makes casting base to derived not possible.

    Hope this helps.

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/


    Friday, August 19, 2011 6:16 PM
    Moderator
  • so if I start out with a base class object that I need to convert to a child class object what do I do?  write a method to do the conversion for me? 

    in which my code would look like

    childInstance = baseInstance.convertToChild(); .....????


    Peter G. Simmon
    Friday, August 19, 2011 7:03 PM
  • I would add a constructor to the derived/child class that accepted an instance of a base class object.  The code you have posted looks like it would make for good content. 

    Assembler_Program_Source_Element MyAssemblerProgramSourceElement = new Assembler_Program_Source_Element();
          MyAssemblerProgramSourceElement.Element_Location = MySourceElement.Element_Location;
          MyAssemblerProgramSourceElement.Element_Name = MySourceElement.Element_Name;
          MyAssemblerProgramSourceElement.Element_Type = MySourceElement.Element_Type;
          MyAssemblerProgramSourceElement.Element_Version = MySourceElement.Element_Version;
          MyAssemblerProgramSourceElement.File_Commands = MySourceElement.File_Commands;


    The constructor could be private or public, and your static method could simply call the constructor to obtain a new instance.

     

    Rudy   =8^D


    Mark the best replies as answers. "Fooling computers since 1971."

    http://thesharpercoder.blogspot.com/


    • Marked as answer by PeterSimmon Friday, August 19, 2011 8:39 PM
    Friday, August 19, 2011 7:46 PM
    Moderator
  • If you are starting out with a base class you cannot convert the same instance to a child class. I think RudeDog2 has explained through a goos example.

    If you really have such a requirement,

    1. Write api or constructor in the derived class which takes an instance of the base class. This implementation will read the values from the base class and populate the current class's values.

    2. In the client code instantiate the derived class and use the api / constructor from step 1 to pass the existing base class.

    An alternative option is to start out with a child class but use it as the base class in first part of your program.

    Friday, August 19, 2011 7:59 PM
  • Friday, August 19, 2011 8:15 PM
  • thanks Rudi, I never thought about that!! 
    Peter G. Simmon
    Friday, August 19, 2011 8:39 PM