Coding Memo

매개변수 한정자 (ref, in, out) 본문

Language/C#

매개변수 한정자 (ref, in, out)

minttea25 2023. 5. 2. 14:19

매개 변수 앞에 한정자를 붙여 전달 방식을 지정할 수 있다.

 

ref  인수 할당 필요, 매개 변수를 다른 개체로 재할당 가능
in 인수 할당 필요, read only
out 인수 할당이 필수가 아님, 대신 호출된 메서드에서는 이 매개 변수에 값을 반드시 할당 해야함

params: 매개 변수의 개수를 가변으로 지정

ex) int Add(params int[] nums)

 

out은 Try~~(out ~~) 함수를 생각하면 이해하기 편할 것이다. ex) TryGetValue(), TryGetComponent() …

 

ref는 C의 포인터나 참조로 생각하면 쉽다.

out은 C언어 함수에서 값을 할당하는 인자로 생각하면 쉬울거 같은데 값 할당이 필수가 아닌 C와 달리 C#에서는 out 키워드가 있으면 반들시 값을 할당해야 한다. (null, default 할당 가능)

 

NOTE: 선언할 때와 호출 할때 모두 한정자를 동일하게 붙여주어야 한다.


using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            Console.WriteLine($"Before a={a}");

            Change(a);
            Console.WriteLine($"After Change() a={a}");

            a = 1;
            ChangeRef(ref a);
            Console.WriteLine($"After ChangeRef() a={a}");

            a = 1;
            GetY(a, out int b);
            Console.WriteLine($"GetY b={b}");
        }

        static void Change(int x) { x = 10; }
        static void ChangeRef(ref int x) { x = 10; }
        static void GetY(int x, out int y) { y = x; }
    }
}

RESULT

Before a=1
After Change() a=1
After ChangeRef() a=10
GetY b=1

 

ref로 통해 전달된 값은 실제로 값이 바뀌었다.

 

 


namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Sum(1, 2, 3, 4, 5));
        }

        static int Sum(params int[] a)
        {
            int sum = 0;
            foreach (int v in a) sum += v;
            return sum;
        }
    }
}

 RESULT

15

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters

 

Method Parameters - C# Reference

Table of contents Method Parameters (C# Reference) Article 04/12/2023 13 contributors Feedback In this article --> In C#, arguments can be passed to parameters either by value or by reference. Remember that C# types can be either reference types (class) or

learn.microsoft.com