How to pass Objects as type System.Object?
(Monday, January 30, 2006)
Found the following interesting discussion in the Newsgroups:
Passing Objects as type System.Object by:Stephen Travis
| I'm trying to ReDim a child object after passing the parent object as System.Object and it throws a System.InvalidCastException:
Cast from type 'Object()' to type 'ChildType()' is not valid. If I pass the parent object as its type, the ReDim succeeds. How can I
ReDim a child object from a parent object passed as System.Object?
Here's the problem...
Private Sub Page_Load
Dim NewParent As New ParentType
addTwoChildrenSucceeds(NewParent)
addTwoChildrenFails(NewParent)
End Sub
Public Sub addTwoChildrenFails(ByVal parentobject As System.Object)
ReDim parentobject.Child(1) ' Throws the exception.
parentobject.Child(0) = New ChildType
parentobject.Child(0).ChildName = "Brian"
parentobject.Child(1) = New ChildType
parentobject.Child(1).ChildName = "Gail"
End Sub
Public Sub addTwoChildrenSucceeds(ByVal parentobject As ParentType)
ReDim parentobject.Child(1)
parentobject.Child(0) = New ChildType
parentobject.Child(0).ChildName = "Brian"
parentobject.Child(1) = New ChildType
parentobject.Child(1).ChildName = "Gail"
End Sub
Public Class ParentType
Public ParentName As System.String
Public Child() As ChildType
End Class
Public Class ChildType
Public ChildName As System.String
End Class
| | | Reply: by:The Grim Reaper
| | | You're nearly there...
Public Sub addTwoChildrenFails(ByVal parentobject As System.Object)
parentobject = DirectCast(parentobject, ParentType)
ReDim parentobject.Child(1) ' Doesn't throw an exception any
more
parentobject.Child(0) = New ChildType
parentobject.Child(0).ChildName = "Brian"
parentobject.Child(1) = New ChildType
parentobject.Child(1).ChildName = "Gail"
End Sub
Untested... I'm sure someone else will contradict me.... tis the way of it
:D
_____________________________
The Grim Reaper
| | | Reply: by:Tom Spink
| | | Hi, May I ask why you pass it as an object... will you have different
classes being ReDim'med?
--
HTH,
-- Tom Spink
|
|
|
|
0 Comments:
Post a Comment
<< Home