Notice
Recent Posts
Recent Comments
Link
관리 메뉴

nomad-programmer

[Programming/C#] 참조자 본문

Programming/C#

[Programming/C#] 참조자

scii 2020. 9. 7. 15:22

C#에서 참조에 의한 매개 변수 전달은 아주 쉽다. ref 키워드만 입력해주면 된다. 물론 C++도 쉽지만...

C#의 ref 키워드는 C++의 &(참조자)와 똑같은 개념이다.

매개 변수를 메소드에 참조로 전달

using System;

namespace SwapRef
{
    class MainApp
    {
        static void Swap(ref int a, ref int b)
        {
            int temp = b;
            b = a;
            a = temp;
        }
        
        static void Main(string[] args)
        {
            int x = 3;
            int y = 4;
            
            Console.WriteLine($"x:{x}, y:{y}");
            
            Swap(ref x, ref y);
            
            Console.WriteLine($"x:{x}, y:{y}");
        }
    }
}

/* 결과

x:3, y:4
x:4, x:3

*/

 

메소드의 결과를 참조로 반환

ref 한정자를 이용해 메소드를 선언하고, return문이 반환하는 변수 앞에도 ref 키워드를 명시해야 한다. 그리고 지역 변수와 호출할 메소드의 이름 앞에 ref 키워드를 위치시켜야 한다. 참고로 이렇게 참조로 반환받은 결과를 담는 지역 변수를 "참조 지역 변수(ref local)"라 부른다.

using System;

namespace CSharpExam
{
    class Product
    {
        private int price = 100;

        public ref int GetPrice()
        {
            return ref price;
        }

        public void PrintPrice()
        {
            Console.WriteLine($"\nPrice: {price}\n");
        }
    }

    class RefReturnExam
    {
        static int Main(string[] args)
        {
            Product carrot = new Product();
            // ref_local_price변수는 참조 지역 변수
            ref int ref_local_price = ref carrot.GetPrice();
            int normal_local_price = carrot.GetPrice();

            carrot.PrintPrice();

            Console.WriteLine($"Ref Local Price: {ref_local_price}");
            Console.WriteLine($"Normal Local Price: {normal_local_price}");

            ref_local_price = 200;

            carrot.PrintPrice();

            Console.WriteLine($"Ref Local Price: {ref_local_price}");
            Console.WriteLine($"Normal Local Price: {normal_local_price}");

            return 0;
        }
    }
}

/* 결과

Price: 100

Ref Local Price: 100
Normal Local Price: 100

Price: 200

Ref Local Price: 200
Normal Local Price: 100

*/
Comments