Is there a way to set up a C# function to accept any number of parameters? For example, could you set up a function such that the following all work –
x = AddUp(2, 3)
x = AddUp(5, 7, 8, 2)
x = AddUp(43, 545, 23, 656, 23, 64, 234, 44)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use a parameter array with the
paramsmodifier:If you want to make sure there’s at least one value (rather than a possibly empty array) then specify that separately:
(Set
sumtofirstValueto start with in the implementation.)Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:
into something like:
You can call it with a perfectly normal array though – so the latter syntax is valid in source code as well.