값에 의한 전달, 참조에 의한 전달, 참조 반환값: ref

Fruit·2023년 3월 28일

✨ Hello C#!

목록 보기
18/34
post-thumbnail

🌸 값에 의한 전달

  • 메서드를 호출할 때 데이터를 복사해서 매개변수에 넘긴다.
using System;

namespace SwapByValue
{
    class MainApp
    {
        public static void Swap (int a, 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(x, y);		// x, y의 값은 변경되지 않음

            Console.WriteLine($"x: {x}, y: {y}");
        }
    }
}

[실행 결과]
x: 3, y: 4
x: 3, y: 4



🌸 참조에 의한 전달: ref

  • 매개변수가 메서드에 넘겨진 원본 변수를 직접 참조한다.

ref 매개변수

using System;

namespace SwapByRef
{
    class MainApp
    {
        public 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);		// x, y의 값이 변경됨

            Console.WriteLine($"x: {x}, y: {y}");
        }
    }
}

[실행 결과]
x: 3, y: 4
x: 4, y: 3



🌸 참조 반환값: ref

  • 메서드의 결과를 참조로 반환한다.

ref 메서드, return ref

using System;

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

        public ref int GetPrice()
        {
            return ref price;
        }
    }
    class MainApp
    {
        static void Main (string[] args)
        {
            Product fruit = new Product();

            ref int ref_local_price = ref fruit.GetPrice();
            int local_price = fruit.GetPrice();                 // ref 키워드를 사용하지 않으면 평범한 메서드처럼 동작

            Console.WriteLine($"Ref Local Price: {ref_local_price}");
            Console.WriteLine($"Local Price: {local_price}");               // ref 키워드를 사용하지 않으면 평범한 메서드처럼 동작

            ref_local_price = 200;

            Console.WriteLine($"\nRef Local Price: {ref_local_price}");
            Console.WriteLine($"Local Price: {local_price}");

        }
    }
}

[실행 결과]
Ref Local Price: 100
Local Price: 100

Ref Local Price: 200
Local Price: 100
profile
🌼인생 참 🌻꽃🌻 같다🌼

0개의 댓글