C# 값전달, 참조전달 ref, out, 메소드 파라미터, C#학원, 시샵학원, C#교육, 시샵교육, 닷넷교육동영상
http://ojc.asia/bbs/board.php?bo_table=LecCsharp&wr_id=402
ojc.asia
https://www.youtube.com/watch?v=A69WD6rJOIY&list=PLxU-iZCqT52DJyR6gqJy0MCL8RiTVXdos&index=13

https://www.youtube.com/watch?v=zBOKgEgBINI&list=PLxU-iZCqT52DJyR6gqJy0MCL8RiTVXdos&index=12

값 전달, 참조전달(ref, out)
C#이나 자바에서 메소드의 인자로 객체참조변수가 넘어가면 참조로 파라미터가 전달되며 기본데이터 형식(int등)이 넘어가면 값 자체가 전달된다.
아래 예제는 Swap 함수로 값 자체가 전달된다.
namespace RefTest
{
class Program
{
static void Swap(int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
static void Main(string[] args)
{
int a = 10; int b = 20;
Console.WriteLine("a={0}, b={1}", a, b);
Swap(a, b);
Console.WriteLine("a={0}, b={1}", a, b);
}
}
}
[결과]
a=10, b=20
a=10, b=20
C#에서 기본데이터 형식을 참조로 넘기려면 ref, out을 사용한다.
- out 키워드
참조에 의한 전달을 할 때 사용하는 키워드로 참조로 값을 넘길 때 참조할 대상을 초기화할 필요는 없다. 함수로부터 값을 얻어낼 때 주로 사용하는 Out 파라미터로 특별히 초기화를 할 필요가 없다.
빈 깡통을 넘겨서 값을 얻어낼 때 사용(오라클 같은 DBMS 프로시저의 OUT 매개변수)하며 초기화된 배열을 넘기는 것도 가능하다.
- ref 키워드
참조로 값이 전달되며, 참조할 변수는 반드시 초기화되어 있어야 한다.
namespace RefTest
{
class Test
{
private static void Sum(int num, ref int tot)
{
tot += num;
}
static void Main()
{
int tot = 0;
Sum(10, ref tot);
Console.WriteLine("Sum : {0}", tot);
Sum(20, ref tot);
Console.WriteLine("Sum : {0}", tot);
}
}
}
namespace RefTest
{
class Test
{
private static void Add(int num1, int num2, out int tot)
{
//tot는 out 타입으로 메소드 실행중 초기화 된다.
tot = num1 + num2;
}
static void Main()
{
int tot = 999; //기본적으로 초기화 필요없고, 초기화 되어있어도 무시된다.
Add(10, 20, out tot);
Console.WriteLine("Sum : {0}", tot);
Add(20, 30, out tot);
Console.WriteLine("Sum : {0}", tot);
}
}
}
[결과]
Sum : 30
Sum : 50