C#에서 메서드와 매개변수 사용
발행: (2026년 2월 3일 오전 03:33 GMT+9)
3 min read
원문: Dev.to
Source: Dev.to
메서드 정의 및 호출
static void Greet()
{
Console.WriteLine("Hello!");
}
static void Main()
{
Greet(); // method call
}
// Output:
Hello!
매개변수가 있는 메서드
static void Greet(string name)
{
Console.WriteLine("Hello " + name + "!");
}
static void Main()
{
Greet("Alice");
Greet("Bob");
}
// Output:
Hello Alice!
Hello Bob!
기본 매개변수
static void PrintMessage(string text = "Default message")
{
Console.WriteLine(text);
}
static void Main()
{
PrintMessage("Hello world!");
PrintMessage();
}
// Output:
Hello world!
Default message
매개변수 vs 인수
static void Square(int number) // parameter: number
{
Console.WriteLine(number * number);
}
static void Main()
{
Square(4); // argument: 4
}
// Output:
16
오버로드
static int Multiply(int a, int b)
{
return a * b;
}
static int Multiply(int a, int b, int c)
{
return a * b * c;
}
static void Main()
{
Console.WriteLine(Multiply(3, 4));
Console.WriteLine(Multiply(2, 3, 4));
}
// Output:
12
24
재귀
static int Factorial(int n)
{
if (n <= 1)
return 1; // base case
return n * Factorial(n - 1); // recursive call
}
static void Main()
{
Console.WriteLine(Factorial(5)); // 120
}
// Output:
120
ref 및 out 매개변수
// ref example
static void Increment(ref int number)
{
number++;
}
// out example
static void ReadValue(out int result)
{
result = 42;
}
static void Main()
{
int x = 5;
Increment(ref x);
Console.WriteLine(x); // 6
int y;
ReadValue(out y);
Console.WriteLine(y); // 42
}
// Output:
6
42
params를 사용한 다중 매개변수
예시: 숫자 합산
static int Add(params int[] numbers)
{
int sum = 0;
foreach (int n in numbers)
sum += n;
return sum;
}
static void Main()
{
Console.WriteLine(Add(1, 2, 3)); // 6
Console.WriteLine(Add(5, 10, 15, 20)); // 50
}
// Output:
6
50
예시: 문자열 결합
static string JoinWords(params string[] words)
{
return string.Join(" ", words);
}
static void Main()
{
Console.WriteLine(JoinWords("C#", "is", "a", "powerful", "language."));
// Output: C# is a powerful language.
}
// Output:
C# is a powerful language.
로컬 함수
static void Main()
{
int Multiply(int a, int b) // local function
{
return a * b;
}
Console.WriteLine(Multiply(3, 4)); // 12
}
// Output:
12
- 메서드는 재사용 가능한 코드 블록입니다.
- 매개변수는 데이터를 메서드에 전달하는 데 사용됩니다.
return은 값을 반환하는 데 사용됩니다.- 기본 매개변수는 코드를 유연하게 만듭니다.
- 오버로드를 통해 같은 이름이지만 다른 매개변수를 가진 메서드를 정의할 수 있습니다.
ref와out매개변수는 참조를 통해 값을 수정할 수 있게 합니다.params는 가변 개수의 매개변수를 허용합니다.- 로컬 함수는 다른 메서드 내부에 정의된 보조 메서드입니다.
- 재귀는 문제를 해결하기 위해 메서드가 자신을 호출하는 것을 의미합니다.