c-sharp
  1. c-sharp-array-to-function

C# Array as a Function Parameter

In C#, you can pass arrays as parameters to functions, allowing you to work with collections of elements within the scope of a method. This guide covers the syntax, usage, and important considerations when passing arrays to functions in C#.

Syntax

// Define a function with an array parameter
ReturnType functionName(DataType[] arrayParameter)
{
    // Function logic using arrayParameter
}

Example

using System;

class ArrayFunctionExample
{
    // Function that takes an array of integers and calculates their sum
    static int CalculateSum(int[] numbers)
    {
        int sum = 0;
        foreach (int number in numbers)
        {
            sum += number;
        }
        return sum;
    }

    static void Main()
    {
        // Example usage
        int[] values = { 1, 2, 3, 4, 5 };
        int result = CalculateSum(values);
        Console.WriteLine("Sum of array elements: " + result);
    }
}

Output

The output will be the sum of the array elements, calculated by the CalculateSum function.

Explanation

  • The CalculateSum function takes an array of integers as a parameter.
  • Inside the function, a foreach loop is used to iterate through the elements of the array and calculate their sum.
  • The example in the Main method demonstrates calling the function with an array of integers.

Use

Passing arrays as function parameters in C# is useful when:

  • You want to encapsulate a specific operation or logic that involves an array.
  • You need to perform array-related computations within a function.
  • Reusability is a consideration, and the same array-processing logic can be applied to different arrays.

Important Points

  • Arrays are passed by reference, meaning changes made to the array within the function affect the original array.
  • The size of the array is not explicitly specified in the function parameter, so the function can accept arrays of different sizes.
  • Consider using the params keyword if you want the function to accept a variable number of array elements.

Summary

In C#, passing arrays as function parameters enables modular and reusable code. Functions can perform specific operations on arrays without the need to rewrite the same logic for each array. Understanding array parameter syntax and considerations for passing arrays by reference will enhance your ability to work with arrays in C# functions.

Published on: