공부
C# 12 새로운 기능: Primary Constructor
samosa
2024. 12. 3. 13:23
C# 12에서는 Primary Constructor라는 기능이 도입되었다. 이는 클래스 선언과 동시에 생성자를 정의할 수 있는 문법으로, 코드의 간결성과 가독성을 높이는 데 목적이 있다.
Primary Constructor란?
Primary Constructor는 클래스 선언부에 생성자 매개변수를 통합하여 필드 초기화를 간단히 처리하는 기능이다.
기존 방식
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Primary Constructor 사용 방식
public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
주요 특징
- 생성자와 클래스 통합
클래스 선언부에서 생성자 매개변수를 바로 사용 가능하다. public class Rectangle(double width, double height) { public double Area => width * height; }
- 상속 클래스와의 연계
기본 클래스 생성자 호출도 간단히 처리할 수 있다. public class Employee(string name, int id) : Person(name, age: 30) { public int EmployeeId { get; } = id; }
- 초기화 로직 포함 가능
초기화 블록을 활용하여 추가 로직 작성이 가능하다. public class Circle(double radius) { public double Circumference { get; } public Circle { Circumference = 2 * Math.PI * radius; } }
장점
- 코드 간결성 향상
- 클래스 구조를 한눈에 파악 가능
- 간단한 데이터 클래스나 유틸리티 클래스에 적합
활용 사례
- DTO 클래스
public record Product(string Name, decimal Price, int Stock);
- 유틸리티 클래스
public class TemperatureConverter(double celsius) { public double Fahrenheit => celsius * 9 / 5 + 32; }
한계
- 복잡한 초기화 로직에는 부적합
- 기존 생성자 방식과 혼합 사용 시 일관성 유지 필요
Primary Constructor는 간단한 클래스를 작성할 때 강력한 도구가 될 수 있다. 하지만 상황에 따라 기존 방식과 병행하여 사용하는 것이 중요하다.