Passando Arrays usando ref e out (C# Programming Guide)

Como todos os check-out parâmetros, um out parâmetro de um tipo de matriz deve ser atribuído antes que ele é usado; ou seja, ele deve ser atribuído pelo receptor.Por exemplo:

static void TestMethod1(out int[] arr)
{
    arr = new int[10];   // definite assignment of arr
}

Como todos os ref parâmetros, um ref parâmetro de um tipo de matriz deve ser atribuído definitivamente pelo chamador.Portanto, não é necessário, sem dúvida, seja atribuída pelo receptor.A ref parâmetro de um tipo de matriz pode ser alterado como resultado da chamada.Por exemplo, a matriz pode ser atribuída a Nulo valor ou pode ser inicializado para um array diferente.Por exemplo:

static void TestMethod2(ref int[] arr)
{
    arr = new int[10];   // arr initialized to a different array
}

Dois exemplos a seguir demonstram a diferença entre out e ref quando usados para passar matrizes para métodos.

Exemplo

Neste exemplo, a matriz theArray está declarado no chamador (o Main método) e inicializado na FillArray método.Em seguida, os elementos da matriz são retornados ao chamador e exibidos.

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        FillArray(out theArray);

        // Display the array elements:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1 2 3 4 5        
    */

Neste exemplo, a matriz theArray é inicializado no chamador (o Main método) e passado para o FillArray método usando o ref parâmetro.Alguns dos elementos de matriz são atualizadas na FillArray método.Em seguida, os elementos da matriz são retornados ao chamador e exibidos.

class TestRef
{
    static void FillArray(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[10];
        }
        // Fill the array:
        arr[0] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        FillArray(ref theArray);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < theArray.Length; i++)
        {
            System.Console.Write(theArray[i] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1111 2 3 4 5555
    */

Consulte também

Referência

Matrizes (guia de programação do C#)

Matrizes unidimensionais (guia de programação do C#)

Matrizes multidimensionais (guia de programação do C#)

Matrizes denteadas (guia de programação do C#)

Conceitos

Guia de programação do C#