참조 매개변수
참조 매개변수는 변수의 메모리 위치에 대한 참조입니다. 참조로 매개변수를 전달할 때 값 매개변수와 달리 이러한 매개변수에 대한 새 저장 위치가 생성되지 않습니다.
ref 키워드를 사용하여 참조 매개변수를 선언할 수 있습니다. 다음은 예입니다 -
예
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(ref int x, ref int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;
Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);
/* calling a function to swap the values */
n.swap(ref a, ref b);
Console.WriteLine("After swap, value of a : {0}", a);
Console.WriteLine("After swap, value of b : {0}", b);
Console.ReadLine();
}
}
} 출력
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100
출력 매개변수
return 문은 함수에서 하나의 값만 반환하는 데 사용할 수 있습니다. 그러나 out 매개변수를 사용하면 함수에서 두 개의 값을 반환할 수 있습니다.
다음은 예입니다 -
예
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValue(out int x ) {
int temp = 10;
x = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 150;
Console.WriteLine("Before method call, value of a : {0}", a);
/* calling a function to get the value */
n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();
}
}
} 출력
Before method call, value of a : 150 After method call, value of a : 10