C#/C#200제

[C#] 13일차 - 91. 선택적 인수와 명명된 인수

반나무 2021. 2. 9. 19:43

선택적 인수

메소드를 호출할 때 일부 매개변수에 대한 인수를 생략할 수 있다.

static int MyPower(int x, int y = 2){ ... }

라고 했을때 y의 초기값을 2로 정해줬기 때문에, MyPower(3)과 MyPower(3,2)는 같다.

 

명명된 인수

메소드를 호출할 때 매개변수의 순서를 기억할 필요가 없다.

static int Area(int h, int w)
{
	return h * w;
}

int area = Area(w:5, h:6);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A091_OptionalNamedArguments
{
    class Program
    {
        static int MyPower(int x, int y=2)
        {
            int result = 1;
            for(int i = 0; i <y; i++)
            {
                result *= x;
            }
            return result;
        }

        static int Area(int h, int w)
        {
            return h * w;
        }
        static void Main(string[] args)
        {
            Console.WriteLine(MyPower(4, 2));
            Console.WriteLine(MyPower(4));
            Console.WriteLine(MyPower(3, 4));

            Console.WriteLine(Area(w: 5, h: 6));
            Console.WriteLine(Area(h: 6, w: 5));

        }
    }
}

반응형