Member-only story

Passing Array to Function in C#

Shahzad Aslam
2 min readMay 9, 2024

--

A function can receive a parameter. Similarly a function can also receive an array. We can pass an array as parameter to function. In this activity, when we pass an array to a function we actually passes a reference to the array. we give permission to a function that it can access and can modify the elements of the array.

Passing Array to Function in C#

Passing Array to Function in C# with Example

using System;
public class Program
{
public static void Main(string[] arge)
{
double[] prices = { 8.52, 6.34, 12.00, 9.31, 16.89 };

// Pass the 'numbers' array to a function
MangoPrices(prices);

// Check if the array has been modified
Console.WriteLine("After function call:");

foreach (double price in prices)
{
Console.WriteLine("Price Of Mango = {0}", price);
}
}

static void MangoPrices(double[] arrPrice)
{
// A array with name of 'reprice' can access and modify here.
for (int q = 0; q < arrPrice.Length; q++)
{
arrPrice[q] *= 2; // Double each element of the array
}
}
}

Output

After function call:
Price Of Mango = 17.04
Price Of Mango = 12.68
Price Of Mango = 24.00
Price Of Mango = 18.62
Price Of Mango = 33.78

Summary

The passing of an array to function is technique that we use in programming in C#. But Whenever we pass an array to function we actually passes a reference to the original array. This means that changes made to the array within the function are reflected in the original array outside the function. In scenario, If original array is being modifying then you can prevent a function to doing this by making a copy of the array inside the function.

Thanks for read.

For more useful tutorials please visit the site: C-Sharp Tutorial and also if you find useful to this article please clap and follow the author by hitting below button.

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)

Write a response