C# Passing An Array To A Function

In C#, arrays represent a grouping of elements sharing the same data type stored within a solitary variable. To recycle logic associated with arrays, we can establish a function and transfer the array as an argument. When invoking the function, only the array's identifier (sans brackets) is necessary, as it will be transmitted by reference.

Syntax

It has the following syntax:

Example

function_name(array_name);  // passing array to the method

In this particular syntax,

  • function_name: This signifies the identifier of the function.
  • array_name: It denotes the specific array being provided as a parameter.
  • Note: An array is a reference type. It means when we pass an array to a function, we are actually passing a link to the original array, not a new copy. Therefore, any modification of an array inside the function will affect the original array.

    Passing 1-D Arrays as arguments to the methods

In C# programming, there exist multiple methods for passing one-dimensional arrays as parameters to a function.

The array may be created and set up prior to passing it to the function.

Alternatively, the array can be both created, initialized, and forwarded to the function within a single code line.

Syntax

It has the following syntax:

Example

void Method_name(int[] arr)

{

    // Access or modify array elements

}

Passing an Array to a Function Example in C#

Let's consider a scenario to demonstrate how we can send single-dimensional arrays as parameters to functions.

Example

Example

using System;

class Program	

{

    // Declare Method that takes a 1D array as a parameter

static void PrintArray(int[] num_bers)

    {

Console.WriteLine("Array elements:");

foreach (int num in num_bers)

        {

Console.WriteLine(num);

        }

    }



static void Main()

    {

        // declaration and initialization of a 1-D array

int[] my_array = { 10, 20, 30, 40, 50 };

        // Passing to the array in the method

PrintArray(my_array);

    }

}

Output:

Output

Array elements:

10

20

30

40

50

Explanation:

In this instance, we illustrate the process of passing a one-dimensional array as parameters to a function. Initially, we define a function called PrintArray which accepts a one-dimensional array as an argument. Subsequently, we employ a foreach loop to display each individual element. Within the main function, we create an array of integer type and initialize it with values. These arrays are then supplied to the PrintArray function, following which the program presents the resulting output.

Passing multidimensional arrays as arguments to Methods

In C# development, it's possible to pass multidimensional arrays to a function. The array can be defined and set up beforehand, or it can be both defined, initialized, and passed as arguments in one concise line of code.

Syntax

It has the following syntax:

Example

returnType MethodName(dataType[], arrayName)

{

    // code to be executed

}

Passing Multidimensional arrays as arguments Example in C#

Let's consider an illustration to demonstrate the process of passing multi-dimensional arrays as parameters to functions.

Example

Example

using System;

class Program

{

    // Create a Method 

static void ShowNumbers(int[,] numbers)

    {

        // Iterate over each rows and columns

for (int i = 0; i< 2; i++)  // 2 rows

        {

for (int j = 0; j < 3; j++)  // 3 columns

            {

Console.Write(numbers[i, j] + " ");

            }

Console.WriteLine(); // New line after each row

        }

    }

static void Main()

    {

        // Declaration and Initialization of 2D array

int[,] myNumbers = {

{ 1, 2, 3 },

{ 4, 5, 6 }

        };

        // Pass the 2D array 

ShowNumbers(myNumbers);

    }

}

Output:

Output

1 2 3 

4 5 6

Explanation:

In this instance, we illustrate the process of passing a multi-dimensional array as arguments to a function. Initially, we define a function called DisplayValues that accepts a multi-dimensional array as an argument. Subsequently, we employ a nested for loop to display each element within the array. Within the main function, we instantiate an array of integers and initialize the values. These arrays are then passed as arguments to the DisplayValues function, resulting in the desired output being displayed by the program.

C# Passing an Array to the function Example: Prints the array elements

Let's consider an illustration to explain how to pass an array as an argument to a function in C#.

Example

Example

using System;

public class ArrayExample

{

static void DisplayArr(int[] numbers)

    {

Console.WriteLine("Printing array elements:");

for (int index = 0; index <numbers.Length; index++)

        {

Console.WriteLine(numbers[index]);

        }

    }

public static void Main(string[] args)

    {

int[] data_Set1 = { 100, 200, 300, 400, 500, 600 };

int[] data_Set2 = { 120, 220, 330, 440, 540 };

DisplayArr(data_Set1); // passing array to function

DisplayArr(data_Set2);

    }

}

Output:

Output

Printing array elements:

100

200

300

400

500

600

Printing array elements:

120

220

330

440

540

Explanation:

In this instance, we illustrate the process of passing an array to a function and showcasing its contents. Initially, we define a function called DisplayArr that accepts an array as an argument. Subsequently, we employ a for loop to output each element within the array. Within the main function, we declare two integer variables, dataSet1 and dataSet2, each initialized with distinct values. These arrays are sequentially passed to the DisplayArr function, leading to the display of the desired output.

C# Passing an Array to the function Example: Print the minimum number

Let's consider a scenario to demonstrate how we can provide an array of functions responsible for displaying the smallest number within the array.

Example

Example

using System;

public class ArrayExample

{

static void FindMinimum(int[] numbers)

    {

int smallest = numbers[0];

for (int i = 1; i<numbers.Length; i++)

        {

if (smallest > numbers[i])

            {

smallest = numbers[i];

            }

        }

Console.WriteLine("Minimum element is: " + smallest);

    }

public static void Main(string[] args)

    {

int[] data1 = { 25, 5, 20, 15, 40, 50 };

int[] data2 = { 12, 23, 44, 15, 54 };

FindMinimum(data1); // passing array to function

FindMinimum(data2);

    }

}

Output:

Output

Minimum element is: 5

Minimum element is: 12

Explanation:

In this illustration, we showcase the process of sending arrays to a function to identify and display the smallest element within an array. Initially, we establish a function called FindMinimum, which accepts an array as an argument. Subsequently, we employ a for loop to showcase each individual element. Within the main function, we define an integer variable named data1, and data2 is initialized with distinct sets of values. These arrays are sequentially transferred to the FindMinimum function for evaluation.

C# Passing an Array to a function Example: Print the maximum number

Let's consider a scenario to demonstrate how we can provide an array as an argument to the function responsible for displaying the highest number.

Example

Example

using System;  

public class ArrayExample

{  

static void printMax(int[] arr)  

    {  

int max = arr[0];  

for (int i = 1; i<arr.Length; i++)  

        {  

if (max <arr[i])  

            {  

max = arr[i];  

            }  

        }  

Console.WriteLine("Maximum element is: " + max);  

    }  

public static void Main(string[] args)  

    {  

int[] arr1 = { 25, 10, 20, 15, 40, 50 };  

int[] arr2 = { 12, 23, 64, 11, 54 };  

printMax(arr1);//passing array to function  

printMax(arr2);  

    }  

}

Output:

Output

Maximum element is: 50

Maximum element is: 64

Explanation:

In this instance, we illustrate the process of supplying arrays to a function to identify and display the highest element within an array. Initially, we establish a function called printMax designed to accept an array as an argument. Subsequently, a for loop is employed to showcase each individual element. Within the main function, we declare an integer variable arr1, while arr2 is initialized with distinct values. Successively, these arrays are sequentially transferred to the FindMaximum function.

Conclusion

In summary, transferring arrays to functions enhances the reusability and modularity of code, resulting in clear and easily maintainable programs. In C#, developers can transfer single or multidimensional arrays to methods using either references or parameters. This capability facilitates effective data manipulation and processing within the methods.

C# Passing Array to the Function FAQs

1) Can we pass an array to a function in C#?

Yes, we can pass an array to a function in C#.

Yes, is it possible to alter the array within a function in C#?

Yes, it is possible to alter the array within a function in C#.

To transfer a one-dimensional array to a method, we specify the array type along with the method parameter.

We have the option to declare and set up the array before passing it to the method, or we can accomplish both declaration, initialization, and passing of the array in a single code line.

Example

voidOneDArray(int[] arr) {	

for (inti = 0; i<arr.Length; i++) {

Console.Write(arr[i] + " ");

    }

Console.WriteLine();

}

4) Are arrays passed by reference or by value in C# programming language?

In C#, an array is classified as a reference type. This indicates that when we provide an array as an argument to a function, we are essentially providing a connection to the original array, rather than a duplicate. Consequently, any modifications applied to the array within the function will impact the original array.

5) Is it possible to transmit an array in C# without the need for separate declaration?

Yes, an array can be directly passed in C# by using an inline declaration.

For Example:

Example

Print_arr(new int[] { 1, 2, 3 } );

Input Required

This code uses input(). Please provide values below: