Passing Arrays Using ref and out C#


Seperti semua parameter, parameter out dari tipe data array harus ditetapkan sebelum digunakan; Artinya, itu harus ditugaskan oleh callee. Sebagai contoh:
static void TestMethod1(out int[] arr)
{
    arr = new int[10];   // definite assignment of arr
}
Seperti semua parameter ref, parameter ref dari tipe array pasti ditugaskan oleh pemanggil. Oleh karena itu, tidak perlu dipastikan oleh callee. Parameter ref dari tipe data array dapat diubah sebagai akibat dari panggilan. Sebagai contoh, array dapat diberi nilai null atau dapat diinisialisasi ke array yang berbeda. Sebagai contoh:
static void TestMethod2(ref int[] arr)
{
    arr = new int[10];   // arr initialized to a different array
}
Dua contoh berikut menunjukkan perbedaan antara out dan ref bila digunakan dalam passing array ke metode. Contoh Dalam contoh ini, array theArray dideklarasikan di pemanggil (metode Main), dan diinisialisasi dalam metode FillArray. Kemudian, elemen array dikembalikan ke pemanggil dan ditampilkan.
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        
    */
Dalam contoh ini, array theArray diinisialisasi pada pemanggil (metode Main), dan diteruskan ke metode FillArray dengan menggunakan parameter ref. Beberapa elemen array diperbarui dalam metode FillArray. Kemudian, elemen array dikembalikan ke pemanggil dan ditampilkan.
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
    */
Previous
Next Post »