Function or method with an unknown number of parameters

Is there a way to create a method with an unknown number of parameters?

And if so:

  • How can I access them as part of this method?
  • Should they be of the same type?
+7
source share
2 answers

Yes and yes.

it is possible, and they should all be of the same type, if you need to pass different types, use the object data type instead, and then unpack them inside the function. use ParamArray:

' Accept variable number of arguments Function Sum(ByVal ParamArray nums As Integer()) As Integer Sum = 0 For Each i As Integer In nums Sum += i Next End Function ' Or use Return statement like C# Dim total As Integer = Sum(4, 3, 2, 1) ' returns 10 

for more information see this

+8
source

I know that this has already been answered, and probably most people regularly come here to answer. @pylover's answer is correct, but to add it, you can avoid iterating over all elements simply by calling the Sum() function. Thus,

 Function Sum(ByVal ParamArray nums As Integer()) As Integer Return nums.Sum() End Function 

When calling a function

 Dim total As Integer = Sum(4, 3, 2, 1) 

total returns 10 . Other functions that you can perform on it include Max() , Min() , etc.

+1
source

All Articles