
using System;
namespace SwapByValue
{
class MainApp
{
public static void Swap (int a, int b)
{
int temp = b;
b = a;
a = temp;
}
static void Main (string[] args)
{
int x = 3;
int y = 4;
Console.WriteLine($"x: {x}, y: {y}");
Swap(x, y); // x, y의 값은 변경되지 않음
Console.WriteLine($"x: {x}, y: {y}");
}
}
}
[실행 결과]
x: 3, y: 4
x: 3, y: 4
ref 매개변수
using System;
namespace SwapByRef
{
class MainApp
{
public static void Swap (ref int a, ref int b)
{
int temp = b;
b = a;
a = temp;
}
static void Main (string[] args)
{
int x = 3;
int y = 4;
Console.WriteLine($"x: {x}, y: {y}");
Swap(ref x, ref y); // x, y의 값이 변경됨
Console.WriteLine($"x: {x}, y: {y}");
}
}
}
[실행 결과]
x: 3, y: 4
x: 4, y: 3
ref 메서드, return ref
using System;
namespace RefReturn
{
class Product
{
private int price = 100;
public ref int GetPrice()
{
return ref price;
}
}
class MainApp
{
static void Main (string[] args)
{
Product fruit = new Product();
ref int ref_local_price = ref fruit.GetPrice();
int local_price = fruit.GetPrice(); // ref 키워드를 사용하지 않으면 평범한 메서드처럼 동작
Console.WriteLine($"Ref Local Price: {ref_local_price}");
Console.WriteLine($"Local Price: {local_price}"); // ref 키워드를 사용하지 않으면 평범한 메서드처럼 동작
ref_local_price = 200;
Console.WriteLine($"\nRef Local Price: {ref_local_price}");
Console.WriteLine($"Local Price: {local_price}");
}
}
}
[실행 결과]
Ref Local Price: 100
Local Price: 100
Ref Local Price: 200
Local Price: 100