Home  |  Index  |  Dotnet4all Snippets  |  Submit resources
About  |  Mail us  
Dotnet4all Logo

  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





 
Previous Posts
    - How to create a Username/Login Page?
    - Suggestions to increase the performance of searchi...
    - Where did my Dataset Go?
    - Password Filter DLL
    - An application framework for VB.NET
    - 'System.Net.WebException' - Strange Error
    - Dataset Tablenames <- SQLHelper
    - Add handlers to textboxes in a datagrid
    - Datagrid (windows forms)
    - Inheritance problem with custom control

Archives
    - 2006-01-01
    - 2006-01-08
    - 2006-01-15
    - 2006-01-22
    - 2006-01-29


Disclaimer & Terms of Use  | DotNet4All.Com concept & © 2004 - 2007 by  Zelders²  - Holland