How to pass any number of parameters into a method in C# .NET
April 8, 2015 1 Comment
You must have come across built-in methods in .NET where you can send any number of arguments into a method. E.g. string.Format has an overload where you can pass in a format string and then an array with the “params” modifier.
There’s nothing stopping you from using the same keyword to write a similar method, here’s an example:
public void MethodWithParams(int toBeMultiplied, params int[] multipliers) { foreach (int m in multipliers) { Console.WriteLine(string.Format("{0} x {1} = {2}", toBeMultiplied, m, toBeMultiplied * m)); } }
The above method will go through the integer array in the “multipliers” arrays and multiplies each element with “toBeMultiplied”. Here’s an example on how to call the above method:
MethodWithParams(5, 1, 2, 3, 4, 5, 6);
The first parameter will be set to “toBeMultipled”, the others will be passed into the params array. Some rules to remember:
- The params parameter must come last in the parameters list in the method’s signature
- It’s optional to pass in any argument to the params array, so MethodWithParams(5); is also a valid call.
- There cannot be more than one params array in the parameters list
- There can be any number of other parameters in the method signature as long as the params parameter comes last
View all various C# language feature related posts here.
Reblogged this on Gabriel RB.net and commented:
Ótima dica.