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

--

--

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)