ref 및 out을 사용하여 배열 전달(C# 프로그래밍 가이드)

업데이트: 2007년 11월

모든 out 매개 변수처럼 배열 형식의 out 매개 변수 역시 사용하기 전에 먼저 할당해야 합니다. 즉, 피호출자에 의해 할당되어야 합니다. 예를 들면 다음과 같습니다.

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

모든 ref 매개 변수와 마찬가지로 배열 형식의 ref 매개 변수에는 호출자에 의해 해당 매개 변수 값이 할당되어야 합니다. 즉, 이 경우의 이 매개 변수에는 피호출자에 의해 해당 값이 한정적으로 할당되지 않아도 됩니다. 배열 형식의 ref 매개 변수는 호출의 결과로 바뀔 수 있습니다. 예를 들어, 배열에 null 값을 할당하거나 다른 배열로 초기화할 수 있습니다. 예를 들면 다음과 같습니다.

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

다음 두 예제에서는 메서드에 배열을 전달하는 데 사용된 out과 ref 사이의 차이점을 보여 줍니다.

예제

이 예제에서 theArray 배열은 호출자(Main 메서드)에서 선언되어 FillArray 메서드에서 초기화됩니다. 그런 다음 호출자로 배열 요소가 반환되어 표시됩니다.

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        
    */

이 예제에서 theArray 배열은 호출자(Main 메서드)에서 초기화되고 ref 매개 변수를 사용하여 FillArray 메서드에 전달됩니다. 일부 배열 요소는 FillArray 메서드에서 업데이트됩니다. 그런 다음 호출자로 배열 요소가 반환되어 표시됩니다.

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
    */

참고 항목

개념

C# 프로그래밍 가이드

참조

배열(C# 프로그래밍 가이드)

1차원 배열(C# 프로그래밍 가이드)

다차원 배열(C# 프로그래밍 가이드)

가변 배열(C# 프로그래밍 가이드)