도구
로그인
한국어

코드 배우기C#

C# 다형성

C# 12 기준switch expression · C# 8 부터{ Target: > 20 } · C# 9 부터

같은 DailyKwh() 호출이 기기마다 달라요. virtual 호출과 is·switch 패턴을 봐요.

한 줄 뜻

부모 형식 하나로 여러 자식 객체를 다루면서, 같은 메서드를 불러도 객체가 덮어쓴 동작이 실행되는 성질이에요.

왜 필요한가

기기마다 전력 계산이 다르다고 if (d is Lamp) ... else if (d is Heater) ... 를 반복문마다 적으면, 새 기기를 들일 때마다 그런 곳을 모두 찾아 고쳐야 해요.

계산을 각 클래스의 override 로 옮기면 반복문은 d.DailyKwh() 한 줄로 끝나요. 형식에 따라 다른 말을 해야 할 때만 switch 패턴을 한곳에 둬요.

일상 비유

집 안 콘센트를 떠올려 보세요. 벽은 무엇이 꽂혔는지 묻지 않고 같은 전기를 줘요. 전등은 빛을, 난로는 열을, 스피커는 소리를 내요. 같은 "켜기"에 각자 다르게 움직이는 것이 다형성이에요.

예제 코드

Program.cs · 60줄
List<Device> devices = [new Lamp("Desk lamp", 9), new Heater("Heater", 1500, 22), new Device("Speaker", 20)];double total = 0;foreach (Device d in devices){    double kwh = d.DailyKwh();    total += kwh;    Console.WriteLine($"{d.Name,-10} {kwh,5:F2} kWh  {Hint(d)}");}Console.WriteLine($"Total {total:F2} kWh"); static string Hint(Device d) => d switch{    Heater { Target: > 20 } h => $"set it to {h.Target - 2}C",    Lamp => "use daylight",    _ => "ok",}; class Device{    public string Name { get; }    public int Watts { get; }     public Device(string name, int watts)    {        Name = name;        Watts = watts;    }     public virtual double HoursPerDay => 4;     public virtual double DailyKwh()    {        return Watts * HoursPerDay / 1000;    }} class Lamp : Device{    public Lamp(string name, int watts) : base(name, watts)    {    }     public override double HoursPerDay => 6;} class Heater : Device{    public int Target { get; }     public Heater(string name, int watts, int target) : base(name, watts)    {        Target = target;    }     public override double DailyKwh()    {        double hours = Target > 20 ? 5 : 3;        return Watts * hours / 1000;    }}

언제 사용하나

  • 종류는 여럿인데 다루는 코드는 하나로 두고 싶을 때(기기, 도형, 결제 수단, 알림)
  • 새 종류가 자주 늘어나는 곳
  • 형식에 따라 화면 글만 조금 다를 때는 switch 식 패턴 한 곳으로 모아요

is 패턴(d is Heater h)은 확인과 변수 만들기를 한 번에 해요. as 는 실패하면 null 을 줘서 null 검사를 따로 해야 해요.

패턴 매칭이 여러 곳에 똑같이 되풀이되면 그 동작은 virtual 메서드로 옮길 때가 됐다는 신호예요.

자주 하는 실수

확인 없이 ( ) 로 형식을 바꿈

실제 객체가 그 형식이 아니면 실행하다 InvalidCastException 으로 멈춰요. is Heater h 는 확인과 형식 바꾸기를 한 번에 하고, 아니면 false 를 줘요.

틀린 코드

List<Device> all = [new Lamp("Desk", 9), new Heater("Mini", 800, 18)];var h = (Heater)all[0];Console.WriteLine(h.Target);

실행하면Unhandled exception. System.InvalidCastException: Unable to cast object of type 'Lamp' to type 'Heater'.

고친 코드

List<Device> all = [new Lamp("Desk", 9), new Heater("Mini", 800, 18)];if (all[0] is Heater h){    Console.WriteLine(h.Target);}else{    Console.WriteLine($"{all[0].Name} is not a heater");}

실행하면Desk is not a heater

넓은 갈래를 앞에 둠

switch 식은 위에서부터 맞춰 봐요. Device 가 먼저 있으면 난로도 거기서 걸리니, 컴파일러가 뒤 갈래는 쓸모없다고 오류를 내요. 좁은 형식을 앞에, _ 는 맨 끝에 둬요.

틀린 코드

Console.WriteLine(Kind(new Heater("Mini", 800, 18))); static string Kind(Device d) => d switch{    Device => "device",    Heater => "heater",};

C# 컴파일러가 내는 오류error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.

고친 코드

Console.WriteLine(Kind(new Heater("Mini", 800, 18))); static string Kind(Device d) => d switch{    Heater => "heater",    _ => "device",};

실행하면heater

GetType() == 로 형식을 견줌

GetType() == typeof(Lamp) 는 그 형식일 때만 참이라 Lamp 를 물려받은 SmartLamp 를 빼먹어요. "이 형식이거나 그 자식인가"는 is Lamp 로 물어요.

틀린 코드

List<Device> all = [new Lamp("Desk", 9), new SmartLamp("Hall", 7)];int lamps = all.Count(d => d.GetType() == typeof(Lamp));Console.WriteLine($"lamps: {lamps}"); class SmartLamp(string name, int watts) : Lamp(name, watts);

실행하면lamps: 1

고친 코드

List<Device> all = [new Lamp("Desk", 9), new SmartLamp("Hall", 7)];int lamps = all.Count(d => d is Lamp);Console.WriteLine($"lamps: {lamps}"); class SmartLamp(string name, int watts) : Lamp(name, watts);

실행하면lamps: 2

확인 문제

문제 1

Device 형식 변수에 목표 18도 난로를 담고 DailyKwh() 를 부르면?

Device d = new Heater("Mini", 800, 18);Console.WriteLine(d.DailyKwh());

답과 까닭 보기

답: 2. 2.4 변수 형식과 상관없이 객체(Heater)의 override 가 불려요. 목표 온도가 20 이하라 3시간, 800 × 3 ÷ 1000 = 2.4 예요. 부모 계산이었다면 4시간이라 3.2 가 나왔을 거예요.

문제 2

switch 식은 무엇을 돌려줄까요?

object x = 42;string size = x switch{    int n when n > 40 => "big",    int => "small",    _ => "not a number",};Console.WriteLine(size);

답과 까닭 보기

답: 1. big 42 는 int 이고 when n > 40 조건도 맞아서 첫 갈래에서 끝나요. 위에서부터 처음 맞는 갈래 하나만 사용해요.

자주 묻는 것

패턴 매칭을 사용하면 다형성이 필요 없나요?

둘은 할 일이 달라요. 형식마다 다른 동작은 virtual·override 로 각 클래스에 두고, 한 곳에서만 형식에 따라 갈리는 일(화면 글, 기록)은 switch 패턴으로 모아요.

is 와 as 는 무엇이 다른가요?

is 는 참·거짓을 주고 d is Heater h 처럼 변수까지 만들어요. as 는 실패하면 null 을 줘서 null 검사를 따로 해야 해요. 요즘은 is 패턴을 더 많이 사용해요.

switch 식에서 _ 는 무엇인가요?

앞의 어떤 갈래에도 안 맞을 때 사용하는 나머지 갈래예요. 빠뜨리면 컴파일러가 경고를 내고, 실행하다 안 맞으면 예외가 나요.