namespace CSharp
{
internal class Program
{
static void AddOne(ref int number)// 복사
{
number = number + 1;
}
static int AddOne2(int number)
{
return number + 1;
}
// swap
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
// 반환하고 싶은 값이 여러개일 경우 사용하는 키워드
// ref를 이용해서 값을 넣어준다. -> ref를 사용하지 않아고 컴파일러는 문제 삼지 않음
//
// out
//
static void Divide(int a, int b, out int result1, out int result2) // 사용하지 않으면 에러 발생
{
result1 = a / b;
result2 = a % b;
}
static void Main(string[] args)
{
//int a = 0;
//Program.AddOne(ref a);
//Console.WriteLine(a);
//// 디자인상 AddOne2가 더 좋다
//// 값을 사용할 수 있는 방법이 더 많다
//a = Program.AddOne2(a);
//Console.WriteLine(a);
int num1 = 1;
int num2 = 2;
Program.Swap(ref num1, ref num2);
Console.WriteLine(num1);
Console.WriteLine(num2);
int result1;
int result2;
Divide(10, 3, out result1, out result2);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
}
}
Call by Reference 방식:
사용 시 주의사항:
ref int a ref int number로 선언되었다면, 호출할 때는 ref a와 같이 사용해야 합니다.읽기와 쓰기 모두 가능:
class Program
{
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int num1 = 1;
int num2 = 2;
// ref 키워드를 사용하여 인수 전달
Program.Swap(ref num1, ref num2);
Console.WriteLine(num1); // 2 출력
Console.WriteLine(num2); // 1 출력
}
}
역할:
사용 시 주의사항:
out int resultclass Program
{
static void Divide(int a, int b, out int result1, out int result2)
{
result1 = a / b; // 몫을 result1에 저장
result2 = a % b; // 나머지를 result2에 저장
}
static void Main(string[] args)
{
int num1, num2; // 초기화하지 않아도 됨
// out 키워드를 사용하여 인수 전달
Program.Divide(10, 3, out num1, out num2);
Console.WriteLine(num1); // 3 출력
Console.WriteLine(num2); // 1 출력
}
}
| 구분 | ref | out |
|---|---|---|
| 초기화 여부 | 반드시 초기화된 변수를 전달해야 함 | 초기화되지 않은 변수도 전달 가능 |
| 용도 | 읽기/쓰기가 모두 필요한 경우 | 함수 내부에서 반드시 값 할당 후 결과 전달 시 사용 |
| 값 사용 | 함수 내부에서 값 읽기와 쓰기 모두 가능 | 함수 내부에서 반드시 값 쓰기가 필요 |
| 호출 시 | 인수에도 반드시 ref를 붙여야 함 | 인수에도 반드시 out을 붙여야 함 |
ref:
out: