Is there a way to create a method with unknown number of parameters?
And if it this the case :
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With