참조 매개변수는 변수의 메모리 위치에 대한 참조입니다. 참조로 매개변수를 전달할 때 값 매개변수와 달리 이러한 매개변수에 대한 새 저장 위치가 생성되지 않습니다.
참조 매개변수는 메소드에 제공되는 실제 매개변수와 동일한 메모리 위치를 나타냅니다.
다음은 참조로 매개변수를 전달하는 방법을 보여주는 예입니다. 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