Casting Exception. Simple Code... Why! Why! Why!

S

samadams_2006

I have what seems to be a very simple straight-forward program (shown
below), but I'm getting an error:

Unable to cast object of type 'TestApp1.ParentTable' to type
'TestApp1.ChildTable'.

on the line: objTable = .SelectedOptions (the fifth line from
the top in the following code).

Why is this? I should be able to go from a parent to the child,
correct? .SelectedOptions is of type ParentTable, and objTable is of
type ChildTable. ChildTable inherits from ParentTable. I've also
tried the commands Ctype and DirectCast, and this does not solve the
problem.

Can anyone tell me how to resolve this?

Thanks


--------------------------------------------------
Module Toolbars

Public Sub Main()

Dim objTable As ChildTable

With frmClass
objTable = .SelectedOptions
End With

End Sub

End Module
--------------------------------------------------
Public Class frmClass

Public ReadOnly Property SelectedOptions() As ParentTable
Get

Dim objTable As New ParentTable

With objTable
.strParent = "SelectedOption"
End With

Return objTable

End Get
End Property
End Class
--------------------------------------------------
Option Explicit On

Public Class ChildTable
Inherits ParentTable

Public ReadOnly Property strChild() As String
Get
Return "strChild"
End Get
End Property

End Class

Public Class ParentTable
Public strParent As String
End Class
--------------------------------------------------
 
R

RobinS

This doesn't make sense. First, you obviously don't have Option Strict On
or it wouldn't even compile, because you are not instantiating your class
before trying to use it, i.e. set the property.

Second, you can't define objTable as a ChildTable and then try to assign a
ParentTable to it. They are two different classes, even if the ChildTable
inherits ParentTable.

You can cast ChildTable back to ParentTable, but then you can access the
properties that ParentTable has (strParent), but not the properties that
ChildTable has that ParentTable does not have (strChild).


Robin S.
 
P

Patrick Steele

I should be able to go from a parent to the child,
correct?

No, it's the other way around. You can always go from a child to a
parent. A child is a descendant of a parent -- so it gets whatever the
parent had, plus "more" (anything else that is added).

But, at the hear of it, the "child" is like the parent in that it has
all of the same methods -- which is why you can always go from a child
to a parent.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top