Passing Arrays to Methods in C#

Mannan Ul Haq
0
In C#, arrays are reference types, meaning that when you pass an array to a method, the method receives a reference to the array. This means that if the method modifies the array (e.g., by changing the value of an element), the modifications will be visible outside the method. In other words, C# does not make a copy of the array when you pass it to a method, which is what would happen if arrays were value types. 

One-Dimensional Arrays:

Here is an example of passing a one-dimensional array to a function:

using System;

class Program
{
    static void Main()
    {
        int[] array1D = { 1, 2, 3, 4, 5 };
        PrintArray(array1D);
    }

    static void PrintArray(int[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            Console.WriteLine(array[i]);
        }
    }
}

In this example, `array1D` is a one-dimensional array. This array is passed to the `PrintArray` method which prints all elements of the array. 

Two-Dimensional Arrays:

For two-dimensional arrays, it's pretty similar:

using System;

class Program
{
    static void Main()
    {
        int[,] array2D = { { 1, 2, 3 }, { 4, 5, 6 } };
        PrintArray(array2D);
    }

    static void PrintArray(int[,] array)
    {
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                Console.WriteLine(array[i, j]);
            }
        }
    }
}

In this example, `array2D` is a two-dimensional array. This array is passed to the `PrintArray` method which prints all elements of the array. Note that `GetLength(int dimension)` is used instead of the `Length` property, because `Length` on a multidimensional array would return the total number of elements in the array, not the length of a specific dimension.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !