C# 공부/C# 기본 문법
메소드(Method) - 1 (참조에의한 매개변수 전달, 결과를 참조로 반환, 출력전용 매개변수)
Gyutae Park
2020. 7. 23. 13:51
C와 C++ 에서는 함수 (Function), 파스칼에서는 프로시져(Procedure), 혹은 다른언어에서는 서브루틴(Subroutine)이나
서브프로그램(Subprogram)이라 불렸다.
엄밀하게는 의미차이가 존재하지만, 큰 맥락에서 이 용어들은 같은용어를 지칭함.
A. 참조에 의한 전달 (pass by reference)
1. 매개변수전달
메소드에서 매개변수로 전달된 변수를 직접 참조하여 변수값이 변경됨. (매개변수 자료형 앞에 ref를 붙인다)
ex)
static void Swap(ref int a, ref int b)
{
int temp=b;
b=a;
a=temp;
}
2. 결과를 참조로 반환하기
메소드 호출자에게 반환받은 결과를 참조로 다룰수있도록 한다.
선언시 반환형 앞에 ref, 리턴뒤에 ref 를 추가한다.
ex)
class Product
{
private int price = 100;
public ref int GetPrice() //선언시 반환형앞에 ref
{
return ref price; //선언시 return 뒤에 ref
}
}
static void Main(string[] args)
{
Product carrot = new Product();
ref int ref_local_price = ref carrot.GetPrice(); //ref_local_price는 지역참조변수라 부른다.
int normal_local_price = carrot.GetPrice();
ref_local_price = 200;
Console.WriteLine($"price : {carrot.GetPrice()}"); //200
Console.WriteLine($"ref_local_price : {ref_local_price}"); //200
Console.WriteLine($"normal_local_price : {normal_local_price}"); //100
}
3. 출력전용 매개변수
이미 ref만으로 여러개의 결과를 메소드에서 받아올 수 있지만, C#은 out 키워드를 통해 조금 더 안전한 방법으로 똑같은 일을 할 수 있게 해준다.
ex)
void Divide(int a, int b, out int quotient, out int remainder)
{
quotient = a/b;
remainder = a%b;
}
int a = 20;
int b = 3;
int c; int d;
Divide(a, b, out c, out d);
- ref 와 out 의 차이는 예를들어,
ref 키워드를 매개변수로 넘기는경우에 메소드가 결과를 저장하지 않아도 컴파일러는 경고를하지않지만,
out키워드를 매개변수로 넘기는경우에 메소드가 해당변수에 결과를 저장하지않으면 에러메세지 출력한다.
+) 출력전용매개변수(out)은 미리 선언할필요없이 사용가능하다.
위의 코드에서 c,d 변수선언없이 Divide (a, b, out int c, out int d); 로 사용가능.