Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast an object to its parent object in Visual Basic

Tags:

vb.net

In C# we can do something like this:

Honda a = new Car(); and that works but the same one doesn't work in Visual Basic.NET (I am fairly new to Visual Basic)

Dim a as Honda = new Car and it says Unable to cast object of type 'SampleApp.Car' to type 'SampleApp.Honda'.

What's wrong here?

Here is my sample code:

Module Module1

    Sub Main()
        Dim a As B = New A
        Console.WriteLine(a.DoSOmething())
        Console.ReadLine()
    End Sub
End Module

Class A
    Public Overridable Function DoSOmething() As String
        Return "SOmething"
    End Function
End Class

Class B
    Inherits A

    Public Overrides Function DoSOmething() As String
        Return "Something else"
    End Function

End Class
like image 210
Tarik Avatar asked Jan 17 '26 22:01

Tarik


1 Answers

A Honda is more specific than a car, and may include additional features or behavior. You can cast a Honda to a Car without issue, but not a Car to a Honda.

edit: Example, a Honda may include an ActivateVTEC method, while all Cars will have a Refuel method, so if you were able to create a Honda = new Car, ActivateVTEC would be undefined.

like image 79
Bryan Boettcher Avatar answered Jan 19 '26 18:01

Bryan Boettcher