C# 메서드 완벽 가이드: 정의, 호출, 재귀, 매개변수 전달 방식
메서드(Method)는 작업을 수행하는 문장들의 그룹입니다. 모든 C# 프로그램은 최소한 Main이라는 이름의 메서드를 가진 하나의 클래스를 가집니다.
메서드를 사용하려면 두 단계가 필요합니다.
- 메서드 정의 (Define)
- 메서드 호출 (Call)
메서드 정의 구문
<접근_지정자> <반환_타입> <메서드_이름>(매개변수_리스트)
{
// 메서드 본문
}
메서드 구성 요소
- 접근 지정자: 다른 클래스에서의 가시성 결정 (public, private 등)
- 반환 타입: 메서드가 반환하는 값의 데이터 타입. 반환값 없으면
void
- 메서드 이름: 고유 식별자, 대소문자 구분, 클래스 내 다른 식별자와 중복 불가
- 매개변수 리스트: 괄호 안에 타입, 순서, 개수 지정. 선택 사항(매개변수 없을 수 있음)
- 메서드 본문: 필요한 작업을 완료하는 명령문 집합
기본 예제: 최댓값 찾기
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
메서드 호출
메서드 이름으로 호출합니다. 인스턴스 메서드는 객체 생성 후 호출합니다.
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
static void Main(string[] args)
{
int a = 100, b = 200, ret;
NumberManipulator n = new NumberManipulator();
ret = n.FindMax(a, b); // 메서드 호출
Console.WriteLine("최댓값: {0}", ret);
Console.ReadLine();
}
}
}
출력: 최댓값: 200
다른 클래스에서도 public 메서드는 인스턴스를 통해 호출 가능합니다.
재귀 메서드 호출 (Recursion)
메서드가 자기 자신을 호출하는 것. 팩토리얼 계산 등에서 유용합니다.
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int Factorial(int num)
{
if (num == 1) return 1;
return Factorial(num - 1) * num;
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
Console.WriteLine("6! = {0}", n.Factorial(6)); // 720
Console.WriteLine("7! = {0}", n.Factorial(7)); // 5040
Console.WriteLine("8! = {0}", n.Factorial(8)); // 40320
Console.ReadLine();
}
}
}
매개변수 전달 방식 (Parameter Passing)
매개변수가 있는 메서드 호출 시 인수를 전달하는 세 가지 방식이 있습니다.
| 번호 | 전달 방식 및 설명 |
| 1 |
값 전달 (Value Parameters) 인수의 실제 값을 형식 매개변수에 복사. 함수 내부에서 매개변수 변경해도 원래 인수에 영향 없음. |
| 2 |
참조 전달 (Reference Parameters)
ref 키워드 사용. 인수의 메모리 주소 참조를 전달. 함수 내부 변경이 원래 인수에 반영됨. |
| 3 |
출력 매개변수 (Output Parameters)
out 키워드 사용. 여러 값 반환에 유용. 메서드에서 반드시 값 할당 필요. |
값 전달 vs 참조 전달 예제
using System;
class ParameterDemo
{
// 값 전달
public void ByValue(int num)
{
num = 20;
Console.WriteLine("메서드 내부: {0}", num); // 20
}
// 참조 전달
public void ByRef(ref int num)
{
num = 20;
Console.WriteLine("메서드 내부: {0}", num); // 20
}
static void Main()
{
ParameterDemo d = new ParameterDemo();
int value = 10;
d.ByValue(value);
Console.WriteLine("값 전달 후: {0}", value); // 10 (원본 unchanged)
d.ByRef(ref value);
Console.WriteLine("참조 전달 후: {0}", value); // 20 (원본 changed)
}
}
출력 매개변수 예제
public void GetValues(out int a, out int b)
{
a = 10; // 반드시 할당해야 함
b = 20;
}
// 호출
int x, y;
GetValues(out x, out y); // x=10, y=20
모범 사례: 기본적으로 값 전달을 사용하세요. 원본 수정이 필요할 때만 ref, 초기화되지 않은 변수에 값을 받아올 때만 out을 사용하세요.