?
Solved

Convert base class object to derived class objcet

Posted on 2006-11-24
5
Medium Priority
?
310 Views
Last Modified: 2008-01-09
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!
0
Comment
Question by:caibeier
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 1000 total points
ID: 18010109
That's because you are doing it backwards...

You can cast a DERIVED class to a BASE class, but not the other way around.

A SportsCar "is a" Car...but a Car is NOT necessarily a SportsCar.
0
 
LVL 34

Assisted Solution

by:Sancler
Sancler earned 1000 total points
ID: 18010859
And I wonder, anyway, why - given that SportsCar Inherits Car, and so inherits its methods, including New - you cannot just put

Dim mySportsar As New SportsCar("Ford", "Black")

Roger
0

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question