티스토리 뷰

반응형
차이점에 대한 내용에서 초기화 관련 내용 숙지가 가장 중요

- c#에서 개체를 참조하는 메서드 매개 변수는 항상 참조로 전달됨. 

- 반면 기본 데이터 형식 매개 변수는 값으로 전달됨. (int, string 관련 변수)

- 값 형식을 참조로 전달하려면 ref나 out 키워드 중 하나로 지정해야 함. 

- ref 매개 변수는 사용하기 전에 초기화 해야 함.

- out 매개 변수는 전달하기 전에 초기화할 필요가 없고 이전의 값은 모두 무시함. 

- ref로 받은 매개변수는 함수 내에서 참조 혹은 값의 변경이 가능하지만 초기화되지 않은 값은 받을 수 없음.

- out으로 받은 매개변수는 함수 내에서 반드시 초기화될 목적으로 받음.  함수 내에서 반드시 초기화가 이루어져야 함.



out 을 사용한 예


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        

    */


ref 을 사용한 예


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

    */


728x90
반응형
댓글