S
Stephen Travis
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
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