[c#] 메서드의 중첩 메서드
아래는 중첩 메서드를 사용한 C#의 예시입니다.
using System;
namespace NestedMethods
{
class Program
{
static void Main(string[] args)
{
int result = Calculate(5, 3);
Console.WriteLine($"Result: {result}");
}
static int Calculate(int a, int b)
{
int Sum(int x, int y)
{
return x + y;
}
int Multiply(int x, int y)
{
return x * y;
}
int sumResult = Sum(a, b);
int multiplyResult = Multiply(a, b);
return sumResult + multiplyResult;
}
}
}
위의 예시에서 Calculate
메서드 내부에 Sum
과 Multiply
두 개의 중첩 메서드가 정의되어 있습니다. 이를 통해 Calculate
메서드 내에서 내부적으로 사용되는 Sum
과 Multiply
메서드가 외부에서는 볼 수 없으며, 해당 메서드들은 Calculate
안에서만 사용됩니다.
중첩 메서드를 사용하면 메서드 간의 응집도가 높아지고 재사용성을 높일 수 있으며, 코드의 모듈화와 가독성을 향상시킬 수 있습니다.
참고 자료:
- Microsoft Docs. “메서드 (C# 프로그래밍 가이드)”. https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/classes-and-structs/methods.