C# - Passing Arrays as Function Arguments



Passing Arrays to Functions

You can pass an array to a function like any other variable. Arrays can be passed to a function with different approaches. In this chapter, you will learn about the different approaches along with the examples.

Note: In C#, arrays are reference types, so passing an array to a function means passing its reference, not a copy.

Example

In the following example, we demonstrate the use of passing arrays as function arguments −

using System;

namespace ArrayApplication {
   class MyArray {
      double getAverage(int[] arr, int size) {
         int i;
         double avg;
         int sum = 0;
         
         for (i = 0; i < size; ++i) {
            sum += arr[i];
         }
         avg = (double)sum / size;
         return avg;
      }
      static void Main(string[] args) {
         MyArray app = new MyArray();
         
         /* an int array with 5 elements */
         int [] balance = new int[]{1000, 2, 3, 17, 50};
         double avg;

         /* pass pointer to the array as an argument */
         avg = app.getAverage(balance, 5 ) ;

         /* output the returned value */
         Console.WriteLine( "Average value is: {0} ", avg );
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Average value is: 214.4

Modifying Arrays Inside Functions

Arrays are reference types. So, when an array is passed to a function, it is passed by reference. Any modifications made to the array inside the function affect the original array (i.e., the actual argument).

Example

In the following example, we pass an array to a function that doubles each element. The modifications reflect in the original array:

using System;

class Program {
    static void DoubleValues(int[] arr) {
        for (int i = 0; i < arr.Length; i++) {
            arr[i] *= 2; // Doubling each element
        }
    }

    static void Main() {
        int[] numbers = { 2, 4, 6 };
        DoubleValues(numbers);
        Console.WriteLine(string.Join(", ", numbers));
    }
}

When the above code is compiled and executed, it produces the following result −

4, 8, 12

Passing Arrays with ref Keyword

Since arrays are reference types, you do not need the ref keyword when passing them to a function. However, you can use ref to modify the original array itself explicitly.

Example

In the following example, we modify an array inside a function using the ref keyword:

using System;
class Program
{
   static void ModifyArray(ref int[] arr)
   {
      for (int i = 0; i < arr.Length; i++)
      {
         arr[i] *= 2;
      }
   }

   static void Main()
   {
      int[] numbers = { 1, 2, 3, 4, 5 };
      
      Console.WriteLine("Before modification:");
      foreach (int num in numbers)
      {
         Console.Write(num + " ");
      }

      ModifyArray(ref numbers);

      Console.WriteLine("\nAfter modification:");
      foreach (int num in numbers)
      {
         Console.Write(num + " ");
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Before modification:
1 2 3 4 5 
After modification:
2 4 6 8 10

Passing Arrays as Read-Only (Using params)

You can pass an array with "params" keyword when you want to pass a variable number of arguments (like an array) without passing an array variable.

Example

In the following example, we use the params keyword to pass an array to a method:

using System;
class Program
{
   static void PrintNumbers(params int[] numbers)
   {
      foreach (int num in numbers)
      {
         Console.Write(num + " ");
      }
   }

   static void Main()
   {
      PrintNumbers(1, 2, 3, 4, 5);
   }
}

When the above code is compiled and executed, it produces the following result −

1 2 3 4 5
Advertisements