참조 형식 매개 변수 전달(C# 프로그래밍 가이드)

업데이트: 2007년 11월

참조 형식 변수는 데이터를 직접 포함하지 않고 데이터에 대한 참조를 포함합니다. 값으로 참조-형식 매개 변수를 전달할 경우 클래스 멤버 값과 같은 참조에서 가리키는 데이터를 변경할 수 있으나 참조 값 자체를 변경할 수는 없습니다. 즉, 같은 참조를 사용하여 새 클래스에 메모리를 할당하고 이를 블록 밖에서 지속하도록 할 수 없습니다. 그렇게 하려면 ref 또는 out 키워드를 사용하여 매개 변수를 전달해야 합니다. 편의상 다음 예제에서는 ref를 사용합니다.

예제

다음 예제에서는 참조-형식 매개 변수 arr를 값으로 Change 메서드에 전달하는 것에 대해 설명합니다. 매개 변수가 arr에 대한 참조이므로 배열 요소 값을 변경할 수 있습니다. 그러나 다른 메모리 위치에 매개 변수를 다시 할당하는 것은 메서드 안에서만 가능하며 원래 변수 arr에 영향을 주지는 않습니다.

class PassingRefByVal 
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main() 
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);

        Change(arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
    }
}
/* Output:
    Inside Main, before calling the method, the first element is: 1
    Inside the method, the first element is: -3
    Inside Main, after calling the method, the first element is: 888
*/

이전 예제에서 참조 형식인 arr 배열은 ref 매개 변수 없이 메서드에 전달됩니다. 이러한 경우 arr를 가리키는 참조의 복사본이 메서드로 전달됩니다. 출력은 메서드로 배열 요소 내용(이 경우 1부터 888까지)을 변경할 수 있음을 보여 줍니다. 그러나, Change 메서드 안에서 new 연산자를 사용하여 메모리 일부를 새로 할당하면 변수 pArray은 새 배열을 참조하게 됩니다. 따라서 이후의 모든 변경 사항은 Main에서 만들어진 원본 배열 arr에 영향을 주지 않습니다. 실제로 이 예제에서 두 개의 배열이 만들어지는데, 하나는 Main 안에서 다른 하나는 Change 메서드 안에서 만들어집니다.

다음 예제는 메서드 헤더와 호출에서 ref 키워드를 사용하는 점을 제외하고 이전 예제와 같습니다. 메서드에서의 모든 변경 사항은 호출 프로그램에서 원래 변수에 영향을 줍니다.

class PassingRefByRef 
{
    static void Change(ref int[] pArray)
    {
        // Both of the following changes will affect the original variables:
        pArray[0] = 888;
        pArray = new int[5] {-3, -1, -2, -3, -4};
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main() 
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);

        Change(ref arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);
    }
}
/* Output:
    Inside Main, before calling the method, the first element is: 1
    Inside the method, the first element is: -3
    Inside Main, after calling the method, the first element is: -3
*/

메서드에서의 모든 변경 사항은 Main의 원본 배열에 영향을 줍니다. 실제로 new 연산자를 사용하여 원본 배열을 다시 할당합니다. 따라서, Change 메서드를 호출한 후 arr에 대한 모든 참조는 Change 메서드에서 만들어진 다섯 요소 배열을 가리킵니다.

문자열 맞바꾸기는 참조로 참조-형식 매개 변수를 전달하는 좋은 예입니다. 예제에서 두 문자열 str1과 str2는 Main에서 초기화되고 ref 키워드에 의해 한정된 매개 변수로 SwapStrings 메서드에 전달됩니다. 두 문자열은 메서드와 Main에서 맞바뀝니다.

 class SwappingStrings
 {
     static void SwapStrings(ref string s1, ref string s2)
     // The string parameter is passed by reference.
     // Any changes on parameters will affect the original variables.
     {
         string temp = s1;
         s1 = s2;
         s2 = temp;
         System.Console.WriteLine("Inside the method: {0} {1}", s1, s2);
     }

     static void Main()
     {
         string str1 = "John";
         string str2 = "Smith";
         System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);

         SwapStrings(ref str1, ref str2);   // Passing strings by reference
         System.Console.WriteLine("Inside Main, after swapping: {0} {1}", str1, str2);
     }
 }
 /* Output:
     Inside Main, before swapping: John Smith
     Inside the method: Smith John
     Inside Main, after swapping: Smith John
*/

이 예제에서 호출 프로그램의 변수에 영향을 주려면 참조로 매개 변수를 전달해야 합니다. 메서드 헤더와 메서드 호출 모두에서 ref 키워드를 제거하면 호출 프로그램에서 아무것도 변경되지 않습니다.

문자열에 대한 자세한 내용은 문자열을 참조하십시오.

참고 항목

개념

C# 프로그래밍 가이드

참조

매개 변수 전달(C# 프로그래밍 가이드)

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

ref(C# 참조)

참조 형식(C# 참조)