Passing an array as Object

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Stephen Travis (stravis_at_iname.com)
Date: 08/04/04


Date: Wed, 4 Aug 2004 15:53:48 -0400

I'm trying to write a subroutine that will fill an array of some type with several objects of that type. The subroutine works fine
if I directly reference the array but if I pass the array as an Object, it throws a cast error. The only way I've been able to get
this to work is to return an ArrayList and then use the .CopyTo method of the ArrayList to stuff the ArrayList into my array. I've
tried DirectCast and several other methods to get around this problem with no luck. Is there some way to populate an array in a
subroutine without using a specific type or passing it as Object? Passing it as Object seems to recast it from its original type.

Here's the test case.
Private MyObjects() As SomeObjectType

Public Class SomeObjectType
    Public someproperty As System.String
    Public Sub somemethod()
    End Sub
End Class

Private Sub Page_Load()
    DoSomethingSucceeds()
    DoSomethingFails(MyObjects) ' System.InvalidCastException: Specified cast is not valid.
End Sub

Private Sub DoSomethingSucceeds()
    ReDim MyObjects(0)
    MyObjects(0) = New SomeObjectType
    MyObjects(0).someproperty = "somevalue"

    For Each MyObject As SomeObjectType In MyObjects
        MyObject.somemethod()
    Next
End Sub

Private Sub DoSomethingFails(ByRef arr As Object)
    ReDim arr(0)
    arr(0) = New SomeObjectType
    arr(0).someproperty = "somevalue"

    For Each MyObject As SomeObjectType In arr
        MyObject.somemethod()
    Next
End Sub

End Class



Relevant Pages

  • Re: Why does assigning @_ cause subs parameter to be copied?
    ... no use describing sub returns ... that isn't actually returning a hash which can't be done. ... Arguments to a subroutine are accessible inside the subroutine ... HERE you copied the array to a lexical. ...
    (comp.lang.perl.misc)
  • Re: Replacing a line
    ... #Using core module Tie::File to process a file in this subroutine ... sub process_one_file { ... $cpp_file = shift; ... for (@array) #Each line should come one by one ...
    (comp.lang.perl.misc)
  • Re: Passing an array section
    ... call SUB, N) ... subroutine SUB ... why am I not getting the array sections? ... compiler error. ...
    (comp.lang.fortran)
  • RE: Using array from subroutine
    ... Subject: Using array from subroutine ... sub open_file { ... die "Could Not Open $file: ... @lines is an empty array when the second subroutine is called. ...
    (perl.beginners)
  • Re: Passing an array as Object
    ... always treating it as an object (private myObjects() as Object) did the trick. ... > sub DoSomethingas Object) ... > method to take in an array of objects and it should work fine. ... >> Private MyObjectsAs SomeObjectType ...
    (microsoft.public.dotnet.languages.vb)