Summary: in this tutorial, you’ll learn how to pass an array to a function as an argument.
Passing an array to a function as an argument #
To pass an array to a function, you specify the array parameter with the following syntax:
type [] arrayParameter
The following illustrates how to pass an array to a function:
void PrintArray(decimal[] elements)
{
foreach (var element in elements)
{
Console.WriteLine($"{element:0.##}");
}
}
decimal[] salaries = { 100000, 120000, 150000 };
PrintArray(salaries);
Output:
100000
120000
150000
How it works.
First, define a function called PrintArray() that outputs the elements of an array to the console:
void PrintArray(decimal[] elements)
{
foreach (var element in elements)
{
Console.WriteLine($"{element:0.##}");
}
}
In this PrintArray() function, we use the foreach statement to iterate over the elements of the array and output each of them to the console.
Second, declare a decimal array and initialize it with some values:
decimal[] salaries = { 100000, 120000, 150000 };
Third, pass the salaries array to the PrintArray() function:
PrintArray(salaries);
Note that you can initialize and pass a new array to the function in one step like this:
PrintArray(new decimal[]{ 100000, 120000, 150000 });
Changing the array elements #
Because arrays are reference types, the function can change the values of their elements. For example:
void PrintArray(decimal[] elements)
{
foreach (var element in elements)
{
Console.WriteLine($"{element:0.##}");
}
}
void Increase(decimal[] salaries, decimal percentage = 0.05m)
{
for (int i = 0; i < salaries.Length; i++)
{
salaries[i] = salaries[i] * (1 + percentage);
}
}
decimal[] salaries = { 100000, 120000, 150000 };
Console.WriteLine("Before increment:");
PrintArray(salaries);
Increase(salaries);
Console.WriteLine("After increment:");
PrintArray(salaries);
Output:
Before increment:
100000
120000
150000
After increment:
105000
126000
157500
How it works.
First, define the Increase() function that increases the elements of salaries array by a percentage. By default, the percentage is 5% (or 0.05):
void Increase(decimal[] salaries, decimal percentage = 0.05m)
{
for (int i = 0; i < salaries.Length; i++)
{
salaries[i] = salaries[i] * (1 + percentage);
}
}
Next, declare and initialize an array of salaries:
decimal[] salaries = { 100000, 120000, 150000 };
Then, output the elements of the salaries array using the PrintArray() function:
Console.WriteLine("Before increment:");
PrintArray(salaries);
After that, pass the salaries array to the Increase() function:
Increase(salaries);
Finally, output the elements of the salaries array to the console:
Console.WriteLine("After increment:");
PrintArray(salaries);
Summary #
- Arrays are reference types, functions can change the values of the array elements.
Thank you for your feedback!