In this tutorial, we will learn how to pass an array to function in C#. Before that you need to have an idea on following topics in C#.
We use a function to reuse a block of code in a program. And we can pass an array to the function as a parameter. To pass an array, we need to provide an array name as an argument of a function. Example:
//passing array
function_name(array_name);
C# Passing Array to Function
Let us see it in a demonstration for passing an array to a function in C#. We will pass an array and find the largest element in a function.
//C# program to fincd largest element in an array
using System;
namespace Arrays
{
public class ArrayToFunction
{
static void maxElement(int[] arr, int arr_size)
{
int max = arr[0];
for (int i = 1; i < arr_size; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
Console.WriteLine("Largest element is: " + max);
}
public static void Main(string[] args)
{
int[] arr = { 77, 85, 98, 14, 50 };
//passing array to function
maxElement(arr, 5);
}
}
}
Output:
Largest element is: 98
Another Example: C# Program to find the sum of all the elements present in an array.
In the program below, we will return the sum value from the user-defined function to the main function.
And you can see that, unlike the above example where we declared the function static, here function is non-static which means we need an object reference of the class to access a non-static function. Object obj is created as an instance of ArrayToFunc class.
using System;
namespace Arrays
{
class ArrayToFunc
{
int getSum(int[] arr, int size)
{
int i;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
return sum;
}
static void Main(string[] args)
{
ArrayToFunc obj = new ArrayToFunc();
//ceating and initializing array
int[] arr = new int[] { 10, 20, 30, 40, 50 };
int result;
//Passing array to a function and
//storing the returned value in a result variable
result = obj.getSum(arr, 5);
//Display
Console.WriteLine("Sum of all the elements: {0} ", result);
}
}
}
Output:
Sum of all the elements: 150