참조에 의한 호출(CBR : call by reference)을 지원하기 위해 ref 예약어와 out 예약어가 있다.
✍ 샘플 코드
class Program
{
static void Main(string[] args)
{
int x = 6;
Change(x);
Console.WriteLine(x);
int y = 10;
refChange(ref y);
Console.WriteLine(y);
}
static void Change(int param)
{
param = 0;
}
static void refChange(ref int param)
{
param = 0;
}
}
✅ 결과
6
0
✍ 샘플 코드
class Program
{
static void Main(string[] args)
{
Point a = new Point(10, 12);
Point b = new Point(4, 33);
Change(a);
refChange(ref b);
Console.WriteLine(a.x+", "+a.y);//Point a가 가리키는 값
Console.WriteLine(b.x+", "+b.y);//Point b(=Point p)가 가리키는 값
}
static void Change(Point p)
{
p = new Point();//Point p가 새로운 주소값을 가리키게 됨.
p.x = 0;
p.y = 0;
}
static void refChange(ref Point p)
{
p = new Point();//Point p(=Point b)가 새로운 주소값을 가리키게 됨.
p.x = 0;
p.y = 0;
}
}
class Point
{
public int x;
public int y;
public Point()
{
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
✅ 결과
10, 12
0, 0
✍ 샘플 코드
class Program
{
static void Main(string[] args)
{
int num;
if (Divide(10, 5, out num))
{
Console.WriteLine(num);
}
if (Divide(10, 0, out num)) //false
{
Console.WriteLine(num);
}
if (Divide(0, 10, out num))
{
Console.WriteLine(num);
}
}
static bool Divide(int x, int y, out int result)
{
if (y == 0)
{
result = 0;
return false;
}
result = x / y;
return true;
}
}
✅ 결과
2
0