C# Array Parameter

Like we pass simple variables to methods we can pass the arrays as well. However, if a method is returning an array we will have to declare the return type of method as an Array. In the following example, an array EmployeeNames is being passed to the PrintNames method.

Passing array to a method

string[] EmployeeNames = { "Mark", "Steve", "Akash", "Bill", "Rob" };
PrintNames(EmployeeNames); //Passing the EmployeeNames array to PrintNames method

Defining an array parameter

In the following example, the PrintNames method is expecting a string Array parameter called []Names. So whenever we will call this method we will have to pass a string array as a parameter.

static void PrintNames(string[] Names)
{
    if (Names != null && Names.Length > 0)
    {
        Console.WriteLine("Employee names are\n------------------");
 
        for (int i = 0; i < Names.Length; i++)
        {
            Console.WriteLine(Names[i]);
        }
    }
    else
    {
        Console.Write("There is no element in the array");
    }
}

Returning an array from the method

The following method is returning a string array. To return the array just the array name is required followed by the return keyword.

static string[] GetNames()
{
    string[] EmployeeNames = { "Mark", "Steve", "Akash", "Bill", "Rob" };
    return EmployeeNames;
}

Following example is printing the names all employees by making the use all concepts defined above.

Example

Try It
using System;
 
namespace TLExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            //Getting the names from GetNames method
            string[] EmployeeNames = GetNames();
            //Passing array to a method
            PrintNames(EmployeeNames);
            Console.ReadKey();
        }
 
        static void PrintNames(string[] Names)
        {
            if (Names != null && Names.Length > 0)
            {
                Console.WriteLine("Employee names are\n------------------");
 
                for (int i = 0; i < Names.Length; i++)
                {
                    Console.WriteLine(Names[i]);
                }
            }
            else
            {
                Console.Write("There is no element in the array");
            }
        }
 
        static string[] GetNames()
        {
            string[] EmployeeNames = { "Mark", "Steve", "Akash", "Bill", "Rob" };
            return EmployeeNames;
        }
    }
}
Output

Employee names are
------------------
Mark
Steve
Akash
Bill
Rob

Let's learn about the ArraySegement in the next section.