1. by Value
값을 직접 준다.
|
static void Test(int x) {
x = 8;
}
static void Main() {
int a = 5;
Test(a);
Console.WriteLine(a);
}
|
cs |
직접 값을 전달하여 a값인 5가 출력된다.
2. by Reference
쉽게 생각해서 변수가 전달된다고 생각
|
static void Sqr(ref int x)
{
x = x * x;
}
static void Main()
{
int a = 3;
Sqr(ref a);
Console.WriteLine(a); // Outputs 9
}
|
cs |
ref라는 키워드를 사용하여 참조에 사용된다. 그래서 3을 주고 Sqr 내에서 3*3을 계산하여 9가 출력된다.
(ref 키워드는 method parameter에 메모리 주소를 전달하여 메소드가 실제 변수에 대해 작동할 수 있게 한다.
ref 키워드는 메소드를 정의할 때와 호출할 때 모두 사용된다.)
3. by Output
|
static void GetValues(out int x, out int y)
{
x = 5;
y = 42;
}
static void Main(string[] args)
{
int a, b;
GetValues(out a, out b);
//Now a equals 5, b equals 42
}
|
cs |
out이라는 키워드를 사용하여 말 그대로 함수 내의 값을 출력해준다.