
매개변수의 개수, 형식이 다른 경우에 사용한다.
using System;
namespace Overloading
{
class MainApp
{
static int Plus (int a, int b)
{
return a + b;
}
static double Plus (double a, double b)
{
return a + b;
}
static double Plus (double a, double b, int c)
{
return a + b + c;
}
static void Main(string[] args)
{
Console.WriteLine("1 + 2 = {0}", Plus (1, 2)); // Plus (int a, int b)
Console.WriteLine("1.0 + 2.1 = {0}", Plus(1.0, 2.1)); // Plus (double a, double b)
Console.WriteLine("1 + 2.5 + 3 = {0}", Plus(1, 2.5, 3)); // Plus (double a, double b, int c)
}
}
}
[실행 결과]
1 + 2 = 3
1.0 + 2.1 = 3.1
1 + 2.5 + 3 = 6.5
형식은 같으나 인수의 개수가 달라지는 경우에 사용한다.
using System;
namespace UsingParams
{
class MainApp
{
static int Sum(params int[] args) // 매개변수는 args 배열에 담김
{
int sum = 0;
foreach (int arg in args)
sum += arg;
return sum;
}
static void Main(string[] args)
{
int sum1 = Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sum2 = Sum(1, 2, 3, 4, 5);
Console.WriteLine(sum1);
Console.WriteLine(sum2);
}
}
}
[실행 결과]
55
15