Solved

Convert base class object to derived class objcet

Posted on 2006-11-24
5
292 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
5 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 250 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 250 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
This video discusses moving either the default database or any database to a new volume.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

708 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now