Information Technology Reference
In-Depth Information
When you use an invocation with separate actual parameters for a parameter array, the
compiler does the following:
Takes the list of actual parameters and uses them to create and initialize an array in
the heap.
Stores the reference to the array in the formal parameter on the stack.
If there are no actual parameters at the position corresponding to the formal parameter
array, the compiler creates an array with 0 elements and uses that.
For example, the following code declares a method called
ListInts
, which takes a param-
eter array.
Main
declares three
int
s and passes them to the array.
class MyClass
Parameter array
{
↓
public void ListInts( params int[] inVals )
{
if (inVals != null)
for (int i = 0; i < inVals.Length; i++) // Process the array.
{
inVals[i] = inVals[i] * 10;
Console.WriteLine("{0} ", inVals[i]); // Display new value.
}
}
}
class Program
{
static void Main()
{
int first = 5, second = 6, third = 7; // Declare three ints.
MyClass mc = new MyClass();
mc.ListInts(
first, second, third
); // Call the method.
↑
Actual parameters
Console.WriteLine("{0}, {1}, {2}", first, second, third);
}
}
This code produces the following output:
50
60
70
5, 6, 7