Passing Arrays to Functions in C#: Understanding Pass-by-Reference

Learn how arrays are passed to functions in C# using pass-by-reference. This tutorial explains how modifications within the function affect the original array, providing clear examples and demonstrating the implications for efficient array manipulation.



Passing Arrays to Functions in C#

In C#, arrays are passed to functions by reference. This means the function receives a pointer to the original array's location in memory, not a copy of the array's data. Any modifications made to the array within the function will be reflected in the original array.

Passing Arrays to Methods

To pass an array to a function in C#, you simply provide the array's name as an argument. The function receives a reference to the array.


public void MyMethod(int[] myArray) {
    // ... code to process myArray ...
}

Example 1: Printing Array Elements

This example demonstrates a method that prints the elements of an integer array:


using System;

public class ArrayExample {
    public static void Main(string[] args) {
        int[] numbers = { 1, 2, 3, 4, 5 };
        PrintArray(numbers); // Pass the array to the method
    }
    static void PrintArray(int[] arr) {
        Console.WriteLine("Array elements:");
        foreach (int num in arr) {
            Console.WriteLine(num);
        }
    }
}

Example 2: Finding the Minimum Element

This example finds the minimum element in an integer array:


using System;

public class ArrayExample {
    public static void Main(string[] args) {
        int[] numbers = { 10, 5, 20, 15 };
        FindMin(numbers); // Pass the array to the method
    }
    static void FindMin(int[] arr) {
        // ... (code to find and print the minimum element) ...
    }
}

Example 3: Finding the Maximum Element

This example finds the maximum element in an integer array:


using System;

public class ArrayExample {
    public static void Main(string[] args) {
        int[] numbers = { 10, 5, 20, 15 };
        FindMax(numbers); // Pass the array to the method
    }
    static void FindMax(int[] arr) {
        // ... (code to find and print the maximum element) ...
    }
}