Variable number of arguments in methods. Modifier params. Advantages. Examples of methods with a variable number of arguments
Contents
- 1. What does the variable number of arguments in a method mean? Modifier params. The general form of a method declaration with a variable number of arguments
- 2. What are the advantages of using variable number of arguments in methods?
- 3. Examples of methods that contain a variable number of arguments
- 4. How to determine the number of arguments that were passed to the method? Property Length
- 5. What are the ways to pass a variable number of arguments to a method? Example
- 6. Can the sequence of arguments passed to the method and defined by the params modifier, be of different types?
- 7. Is it possible to pass ordinary arguments and variable length arguments to a method at the same time?
- 8. How many params modifiers can a method have that take a variable number of arguments?
- 9. What error can occur if you pass an empty array of arguments to a method with a variable number of arguments or call a method without parameters?
- Related topics
Search other websites:
1. What does the variable number of arguments in a method mean? Modifier params. The general form of a method declaration with a variable number of arguments
Sometimes there are cases when a method must be called several times and each time a different number of arguments must be passed to this method. Such a situation can be solved by creating an overloaded method implementation.
But it is not always possible to know how many arguments will be passed to the method, especially if the number of arguments can be quite large. In this case, the method is declared with a variable number of arguments.
The general form of a method declaration with a variable number of arguments is:
return_type MethodName(params type[] parameters) { // ... }
where
- MethodName – the name of method;
- return_type – the type returned by the method;
- type – the type of parameters that the method receives. The number of parameters can be varied;
- parameters – a name that corresponds to an array of parameters.
⇑
2. What are the advantages of using variable number of arguments in methods?
Using a variable number of arguments gives the following advantages:
- you can pass a different number of arguments to the same method. This reduces the number of implementations of the method. There is no need for “overloaded” implementations of the method;
- the program code of the method declaration is simplified due to the generalized representation of the array of parameters with the params modifier;
- the number of arguments can be any and be set as the program runs (for example, n arguments). In the case of “overloading” the method, the options for implementing the method with different numbers of arguments are known in advance.
⇑
3. Examples of methods that contain a variable number of arguments
Example 1. The Max() method, which finds the maximum value between an array of arguments.
// method that finds the maximum value between the parameter list double Max(params double[] values) { if (values.Length==0) { Console.WriteLine("Error: no arguments in method call"); return 0; } double max = 0; for (int i = 0; i < values.Length; i++) if (max < values[i]) max = values[i]; return max; }
Calling a method from another program code
double maximum; // finding the maximum between 3 values maximum = Max(8.5, 9.3, 2.9); // maximum = 9.3 // finding the maximum between 5 values maximum = Max(0.3, 2.33, 12.91, 8.93, 7.55); // maximum = 12.91 // finding the maximum between 3 values double[] arguments = { 2.8, 3.6, 1.7, 0.9, 4.45, 7.32, 2.83 }; maximum = Max(arguments); // maximum = 7.32
Example 2. The SumNegative() method, which finds the sum of negative arguments.
// method that finds the sum of negative arguments int SumNegative(params int[] p) { int sum = 0; for (int i = 0; i < p.Length; i++) if (p[i] < 0) sum = sum + p[i]; return sum; }
Использование метода в другом программном коде
int sum = 0; // method call with 6 arguments sum = SumNegative(-3, 2, -1, 4, -8, 5); // sum = -12 // method call with 7 arguments int[] arrayArgs = { -1, 0, -1, 2, -5, -3, 2 }; sum = SumNegative(arrayArgs);
Example 3. An implementation of the IsAscending() method that determines whether the arguments form an increasing sequence.
// a method that determines if arguments form an increasing sequence bool IsAscending(params int[] parameters) { if (parameters.Length < 2) return false; // few arguments, arguments must be more than one for (int i=0; i<parameters.Length-1; i++) if (parameters[i]>=parameters[i+1]) return false; return true; }
Using the method in another program code:
bool fAsc; // method call with 6 arguments fAsc = IsAscending(1, 3, 5, 7, 9, 10); // fAsc = True // method call with 8 arguments int[] A = { 2, 3, 8, 8, 9, 10, 11, 23 }; fAsc = IsAscending(A); // fAsc = False
⇑
4. How to determine the number of arguments that were passed to the method? Property Length
The number of arguments that are passed to the method can be determined using the Length property.
For example. The Average() method is specified, which determines the arithmetic average value. An array of float arguments with the name vals is passed to the method. The number of arguments is available in the property.
vals.Length
The method code is as follows
float Average(params float[]vals) { float avg = 0; // property vals.Length for (int i=0; i<vals.Length; i++) { avg += vals[i]; } return (float)(avg / vals.Length); }
Use of a method in another program code
float[] arguments = { 3.5f, 2.8f, 4.1f, 8.5f }; float avg; avg = Average(arguments); // avg = 4.725
⇑
5. What are the ways to pass a variable number of arguments to a method? Example
A variable number of arguments can be passed to a method in two ways:
- if arguments are separated by commas when calling methods;
- if an array of arguments is passed to the method. The array of arguments has a name.
Example. There are two ways to pass arguments to a method. A method is implemented that calculates the number of positive elements that are passed to the method as parameters.
The implementation of the method is as follows.
int NPositives(params int[] numbers) { int n = 0; for (int i = 0; i < numbers.Length; i++) if (numbers[i] >= 0) n++; return n; }
Calling a method from another program code
// ways to pass arguments to the method int n; // Method 1 - passing through the symbol ',' n = NPositives(-3, 2, 8, 1, -5, -10, 100, 0); // n = 5 n = NPositives(); // n = 0 n = NPositives(-3, 1, 4); // n = 2 // Method 2 - pass using the array int[] A1 = { 8, 2, -3, -4, 5 }; int[] A2 = { -100, 0, -200, 500 }; int[] A3 = { }; n = NPositives(A1); // n = 3 n = NPositives(A2); // n = 2 n = NPositives(A3); // n = 0
⇑
6. Can the sequence of arguments passed to the method and defined by the params modifier, be of different types?
No, it can not. For methods with a variable number of arguments, the following rule applies:
- for each params modifier, there may be a sequence of parameter values of the same type. This type is specified in the declaration of the method as the type of the array of parameters.
For example. The following code for the NPositives() method from paragraph 5 will be incorrect:
n = NPositives(1, -5.75, 3, 0.5); // error, different types of parameters
⇑
7. Is it possible to pass ordinary arguments and variable length arguments to a method at the same time?
Yes, it is. In this case, first must follow the usual arguments. Next must be followed by variable-length arguments with the params modifier. Types of ordinary and variable length arguments may differ.
For example. Below is the implementation of the CalcNumber method. The method calculates the number of occurrences of the specified integer parameter num in the array of parameters numbers. The method accepts two types of arguments:
- ordinary argument is an integer parameter num, the number of occurrences of which must be calculated;
- array of arguments ‘numbers’. The array ‘numbers’ is declared with the params modifier and can have a variable number of arguments.
The implementation of the CalcNumber() method is as follows:
// determining the number of occurrences of the number num in the array of numbers static int CalcNumber(int num, params int[] numbers) { int n = 0; for (int i = 0; i < numbers.Length; i++) if (numbers[i] == num) n++; return n; }
Demonstration of calling method from another program code
int n; // call the method n = CalcNumber(5, -1, -3, 3, 5, 0, 2, 0, 8, 4, 5, 3, 4, 5, 20); // n = 3
⇑
8. How many params modifiers can a method have that take a variable number of arguments?
In method that accepts a variable number of arguments, there can be only one params modifier. In this case, the rule is as follows:
- the parameter with the params modifier must be the last in the list of formal parameters.
So, if two or more params modifiers are specified in the formal parameters list, this rule will not be executed – there will be other modifiers before the last params modifier. This, in turn, will cause an error.
⇑
9. What error can occur if you pass an empty array of parameters to a method with a variable number of arguments or call a method without parameters?
In some methods that accept a variable number of arguments, you need to check for at least one argument. This is due to the fact that you can call the method without arguments. In this case, an empty array will be passed to the method. Reversal to an element of an empty array will result in an error, and, as a result, a runtime exception will be generated.
⇑
Related topics
- Passing parameters to a method. Arguments and formal parameters. Examples. Passing a reference to object of class into a method
- Modifiers ref and out. Examples. Differences between ref and out modifiers
- Passing arrays to methods. Examples. Passing arrays of structures, classes, enumerations to methods. Passing two-dimensional arrays. Returning the array from method
- Optional arguments. Advantages. Examples of using optional arguments. Ambiguity when using optional arguments
- Named arguments. Advantages. Examples