initializing array without knowing it's type

F

farseer

If i have an array of a certain type, is there away of initializing
with without knowing it's type? for example (forgive me if some of
this is syntactically incorrect)

if i have a procedure like this

private sub addElements( target() as Object , elemsToAdd () as object )
begin
if ( arr is Nothing ) then
{initialize with correct type}
end if

Array.resize( target, elemsToAdd.Length)
....
'add elements to target() array
end sub

And from my main routine i'd call it like this:

private dim arr1() as Type1 = nothing;
private dim arr2() as Type2 = nothing;

private dim arrElems1() as Type1 =....
private dim arrElems2() as Type2 =....

addElements( arr1, arrElems1)
addElements( arr2, arrElems2)

As you can see in the scenario above, if both arr1 and arr2 are
Nothing, id like to initialize them in the sub "addElements". How can
i do that?
 
M

Mattias Sjögren

As you can see in the scenario above, if both arr1 and arr2 are
Nothing, id like to initialize them in the sub "addElements". How can
i do that?

You can't do it based on the "target" parameter. A Nothing reference
doesn't carry any type information so that fact that "arr1" is of type
Type1() in the calling code is lost inside the addElements method.

You could do it by using type information from "elemsToAdd". For
example

target =
DirectCast(Array.CreateInstance(elemsToAdd.GetType().GetElementType(),
elemsToAdd.Length), Object())

or

target = DirectCast(Array.CreateInstance(elemsToAdd(0).GetType(),
elemsToAdd.Length), Object())

But even then the change to "target" wouldn't be reflected back to the
caller since you pass it in ByVal. You have to make it ByRef for the
new array reference to be passed back to the caller.


Mattias
 
F

farseer

perfect, thanks. if elemsToAdd were declared as an ICollection, i
assume that getting the type of any element contained within would work
just as well, correct?
 

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