C# 7.0에서 새롭게 도입된 참조 반환(ref return) 기능을 사용하면 메서드가 값을 복사해 돌려주는 대신, 변수 자체에 대한 참조를 반환할 수 있습니다.
호출하는 쪽에서는 반환받은 변수를 일반 값처럼 사용할 수도 있고, 참조로 취급할 수도 있습니다. 또한 반환된 값을 가리키는 새로운 지역 변수, 즉 참조 지역 변수(ref local)를 선언하는 것도 가능합니다.
값 복사 방식의 동작
아래 예제에서 color 변수에는 colors[3]의 값이 복사됩니다. 따라서 color를 변경해도 원본 배열 colors에는 전혀 영향을 미치지 않습니다.
예제
class Program{
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
string color = colors[3];
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}
}출력 결과
blue green yellow orange pink
참조 지역 변수(Ref Local) 활용하기
변수 선언 앞에 ref 키워드를 붙이면 해당 변수가 배열 요소를 직접 참조하게 됩니다. 이제 color를 수정하면 원본 배열의 세 번째 요소가 함께 변경되는 것을 확인할 수 있습니다.
예제
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
ref string color = ref colors[3];
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}출력 결과
blue green yellow Magenta pink
참조 반환(Ref Return)이란?
참조 반환은 메서드가 내부 데이터(예: 배열 요소)에 대한 참조를 호출자에게 그대로 넘겨주는 기능입니다. 메서드의 반환 타입과 return 문 양쪽에 모두 ref 키워드를 사용해야 합니다.
먼저 일반적인 값 반환 방식으로 작성한 경우를 살펴보겠습니다. GetColor 메서드가 값을 복사해 반환하기 때문에 color를 수정해도 원본 배열은 변하지 않습니다.
예제 (값 반환)
class Program{
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
string color = GetColor(colors, 3);
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}
public static string GetColor(string[] col, int index){
return col[index];
}
}출력 결과
blue green yellow orange pink
이번에는 메서드가 참조를 반환하도록 수정해 보겠습니다. 반환 타입과 return 문에 ref를 붙이고, 호출부에서도 ref로 받아오면 됩니다.
예제 (참조 반환)
class Program{
public static void Main(){
var colors = new[] { "blue", "green", "yellow", "orange", "pink" };
ref string color = ref GetColor(colors, 3);
color = "Magenta";
System.Console.WriteLine(String.Join(" ", colors));
Console.ReadLine();
}
public static ref string GetColor(string[] col, int index){
return ref col[index];
}
}출력 결과
blue green yellow Magenta pink
정리
참조 지역 변수와 참조 반환은 큰 크기의 구조체 복사 비용을 줄이거나, 배열·컬렉션의 특정 요소를 메서드 경계를 넘어 직접 수정해야 할 때 매우 유용합니다. 단, 참조 대상이 항상 유효한 수명 범위 안에 있어야 하며, ref 반환값은 반드시 유효한 저장 위치를 가리켜야 한다는 점을 기억하세요.