send array to a function

  • Thread starter Thread starter shachar
  • Start date Start date
S

shachar

hi all.
i'm looking for a simple example of how to pass
optionaly, an array to a function.
if the array isn't there (it's optional) i want to know
about it.
thanks.
 
Shachar,
In addition to ParamArray as Cor suggested.

I would consider Overloading the function or using the Optional keyword.

For example:

' 1. (a) Overload Sum to take 0 parameters
Private Function Sum() As Integer
Return 0
End Function

' 1. (b) Overload Sum to take an array of parameters.
Private Function Sum(ByVal list() As Integer) As Integer
Dim total As Integer
For Each item As Integer In list
total += item
Next
Return total
End Function

' 2. An Optional parameter
Private Function Sum(Optional ByVal list() As Integer = Nothing) As
Integer
If list Is Nothing Then Return 0
Dim total As Integer
For Each item As Integer In list
total += item
Next
Return total
End Function

' 3. An ParamArray
Private Function Sum(ByVal ParamArray list() As Integer) As Integer
Dim total As Integer
For Each item As Integer In list
total += item
Next
Return total
End Function


1, 2 & 3 allow the following:

Dim total As Integer
Dim list() As Integer
total = Sum()
total = Sum(list)

In the above case I prefer 1 as I am letting the compiler decide if I passed
the parameter or not, where as in 2 I have a runtime check to decide if the
parameter was passed or not. 2 will have problems if I can legitimately pass
Nothing as a value for list.

3 also allows:

total = Sum(1,2,3,4,5,6)

I normally use 1 or 3 depending on if I wanted a list of values inline on
the call, rather then explicitly create an array. Depending on what I am
creating I will combine 1 with 3, where I overload on 0, 1, 2, 3 fixed
parameters, then have a ParamArray overload. Similar to the overloads on
String.Format.

Hope this helps
Jay
 
can you show me an example of how to get an array
optionaly into a function.
** i must get an array() .
thanks.
 
Shachar,
I believe I did!

Did you look at the samples I gave, did you try the samples I gave. Did you
try changing one of the samples to the type you want?

Did you try "As Array" instead of "As Integer"?

Can you better explain what you want?

Hope this helps
Jay
 

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

Back
Top