c# 7.0부터는 매개변수뿐만 아니라 로컬 변수와 반환값에 대해서도 참조관계를 맺을 수 있게 되었다.
✍ 로컬 변수에 ref
int a = 4;
ref int b = ref a;
b = 10;
Console.WriteLine(a); // 결과 : 10
Console.WriteLine(b); // 결과 : 10
✍ 반환값에 ref
class Program
{
static void Main(string[] args)
{
Jane j = new Jane();
Console.WriteLine(j.getMostLoved());
j.getMostLoved() = "Mike";//원하는 요소만 얻어 변경
j.PrintMostLoved();
}
}
class Jane
{
private string[] boyfriends = { "Tom", "David", "Richard", "Sam" }; //은닉화
public ref string getMostLoved()
{
return ref boyfriends[0]; //원하는 요소의 참조만 반환
}
public void PrintMostLoved()
{
Console.WriteLine(boyfriends[0]);
✅ 결과
Tom
Mike
✍ 컴파일 오류1 : 지역변수
class Jane
{
private string[] boyfriends = { "Tom", "David", "Richard", "Sam" }; //은닉화
public ref string getMostLoved()
{
string mostLoved = boyfriends[0];
return ref mostLoved; //원하는 요소의 참조만 반환
}
public void PrintMostLoved()
{
Console.WriteLine(boyfriends[0]);
}
}