Parameter arrays allow a variable number of arguments to be passed into a method:
static void Method(params int[] array)
{}
But I fail to see their usefulness, since same result could be achieved by specifying a parameter of particular array type:
static void Method(int[] array)
{}
So what benefits ( if any ) does parameter array have over value parameter of array type?
thank you
Parameters allow us to pass information or instructions into functions and procedures . They are useful for numerical information such as stating the size of an object.
To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. Now to use that procedure: int B[100]; zero(B, 100);
Parameters are usually used for defining some characteristics of the modeled object. They are helpful when object instances have the same behavior described in class, but differ in some parameter values.
A function parameter is a variable used in a function. Function parameters work almost identically to variables defined inside the function, but with one difference: they are always initialized with a value provided by the caller of the function.
You use the ParamArray keyword to denote a parameter array. The array must be declared as an array of type Variant, and it must be the last argument in the procedure definition. The following example shows how you might define a procedure with a parameter array.
You do not have to know the number of elements in the parameter array when you define the procedure. The array size is determined individually by each call to the procedure. You use the ParamArray keyword to denote a parameter array in the parameter list.
The parameter array is automatically optional. Its default value is an empty one-dimensional array of the parameter array's element type. All parameters preceding the parameter array must be required. The parameter array must be the only optional parameter.
The following rules apply: 1 A procedure can define only one parameter array, and it must be the last parameter in the procedure definition. 2 The parameter array must be passed by value. ... 3 The parameter array is automatically optional. ... 4 All parameters preceding the parameter array must be required. ...
It's just a code readability thing. For example, string.Format:
string value = string.Format("SomeFormatString", param1, param2, param3, param4.... param999);
It could be written like this in a different lifetime:
string value = string.Format("SomeFormatString", new string[] { param1, param2, param3 });
In the end, it's just syntactic sugar to make the code easier to read and easier to understand.
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