Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function or Method with unknown number of parameters

Tags:

vb.net

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

And if it this the case :

  • How is it possible to get access to them within this method?
  • Do they have to be from the same type?
like image 757
Pierre Watelet Avatar asked Jun 05 '12 07:06

Pierre Watelet


2 Answers

Yes & yes.

it is possible, and all of them must be the same type, if you need to pass various types use object datatype instead, and then unbox them within 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 info see this

like image 165
pylover Avatar answered Nov 09 '22 01:11

pylover


I know this is already answered and probably most people come here regularly for answer. @pylover answer is correct, but to add on it, you can avoid looping through all the items, by simply calling the Sum() function. Thus;

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

When calling the function

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

total returns 10. Other Functions you can perform on it, includes Max(), Min(), etc

like image 25
Dennys Henry Avatar answered Nov 09 '22 02:11

Dennys Henry