Link to home
Start Free TrialLog in
Avatar of caibeier
caibeier

asked on

Convert base class object to derived class objcet

Hi experts, I was trying to use CType to convert a base class object to a derived class objcet, but got an invalid cast exception.

Here is class definition:
-----------------------------------
Public Class Car
    ...
End Class

Public Class SportsCar
  Inherits Car
   ...
End Class
----------------------------------

Here is program code:
----------------------------------
dim myCar as New Car("Ford", "Black")

Dim mySportsar As SportsCar
mySportsar = CType(myCar, SportsCar)

My purpose is to make mySportsar a Black Ford, and use the member functions defined in SportsCar. But I got the following error

System.InvalidCastException: Specified cast is not valid

Thanks for your help!
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial