변수에 대한 참조를 할당하려면 ref 키워드를 사용하십시오. 참조 매개변수는 변수의 메모리 위치에 대한 참조입니다. 참조로 매개변수를 전달하면 값 매개변수와 달리 이러한 매개변수에 대한 새 저장 위치가 생성되지 않습니다. ref 키워드를 사용하여 참조 매개변수를 선언합니다.
예를 들어 보겠습니다 -
여기에서 ref 키워드 −
를 사용하여 두 값을 교환합니다.예시
using System;
namespace Demo {
class Program {
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) {
Program p = new Program();
/* local variable definition */
int a = 99;
int b = 110;
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 */
p.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 : 99 Before swap, value of b : 110 After swap, value of a : 110 After swap, value of b : 99