Solved

Convert base class object to derived class objcet

Posted on 2006-11-24
5
293 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

920 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