출력 전용 매개변수: out

Fruit·2023년 3월 28일

✨ Hello C#!

목록 보기
19/34
post-thumbnail

🌸 out

  • ref와 달리 메소드가 해당 매개변수에 결과를 저장하지 않으면 에러가 발생한다.
  • 출력 전용 매개변수는 즉석으로 선언할 수 있다.


out 코드

using System;

namespace UsingOut
{
    class MainApp
    {
        static void Divide(int a, int b, out int quotient, out int remainder)
        {
            quotient = a / b;
            remainder = a % b;      // remainder에 결과를 저장하지 않으면 에러 발생
        }

        static void Main(string[] args)
        {
            int a = 20;
            int b = 3;

            Divide(a, b, out int c, out int d);     // 즉석에서 변수 선언 가능

            Console.WriteLine($"{a} / {b} = {c} ... {d}");
        }
    }
}

[실행 결과]
20 / 3 = 6 ... 2

ref 코드

using System;

namespace UsingRef
{
    class MainApp
    {
        static void Divide (int a, int b, ref int quotient, ref int remainder)
        {
            quotient = a / b;
            remainder = a % b;	// remainder에 결과를 저장하지 않아도 에러 발생 X, d는 0 유지
        }

        static void Main (string[] args)
        {
            int a = 20;
            int b = 3;
            int c = 0;
            int d = 0;

            Divide(a, b, ref c, ref d);

            Console.WriteLine($"{a} / {b} = {c} ... {d}");
        }
    }
}

[실행 결과]
20 / 3 = 6 ... 2
profile
🌼인생 참 🌻꽃🌻 같다🌼

0개의 댓글