function with dynamic parameters

Anti-Rich

Well-known member
Joined
Jul 1, 2006
Messages
325
Location
Perth, Australia
Programming Experience
1-3
hi guys,

i was wondering this morning how i could possibly go about creating a function with dynamic parameters to be passed in.

basically, you know how Excel has the Sum(n1 as number...etc) function? that function takes as many parameters as you want it to, so does anyone know how to replicate a similary functionality in vb.net? i think it would be really handy when performing basic calculations (avg,dividing,multiplication etc)

any ideas would be great!
cheers
adam
 
yeah i could, but rather than have to stuff around creating the array and filling it with members, i would just like to be able to do something like this..


VB.NET:
TotalRecieved = Sum(45,20,10)

and have Sum() return the result.

cheers for the feedback. any thoughts?

adam
 
Mark the last method parameter with the ParamArray keyword. Ex:
VB.NET:
Function sum(ByVal ParamArray integers() As Integer) As Integer
    For Each int As Integer In integers
        sum += int
    Next
    Return sum
End Function
VB.NET:
[SIZE=2]
MsgBox(sum(1, 2, 3, 4, 5, 6).ToString) '=21
[/SIZE]
 
excellent!!! thankyou so much johnh, much appreciated. it was exactly what i was looking for...

you know they say... 'you learn something new every day' :)

cheers mate

regards
adam
 
That's actually what I was trying to suggest. I would have expanded on my explanation further, but you said you didn't want to worry about filling the array with numbers (which confused me), so I didn't elaborate. Anyway, glad you found your answer.
 
haha, sorry mate i didnt know about the paramarray keyword, so when you suggested an array of numbers, i thought i would have to create an array, instanciate it, fill it with numbers and then pass it to the function, i didnt realise that you meant in the way of using paramarray,,

hope i didnt offend :)

have a good one
adam
 
Back
Top