생성자 오버로드(Constructor Overloading)란
하나의 클래스에 여러 개의 생성자를 만들어서, 상황에 따라 다른 방식으로 초기화할 수 있게 하는 것입니다.
public class Person
{
public Person() { }
public Person(string name) { }
public Person(string name, int age) { }
}
➡ 호출자가 필요한 만큼의 정보만 제공해 객체를 생성할 수 있습니다.
즉, 공통 초기화 코드를 한 곳에 몰아넣는 전략입니다.
public class User
{
public string Id;
public int Level;
public User()
{
Id = "guest";
Level = 1;
}
public User(string id)
{
Id = id;
Level = 1;
}
public User(string id, int level)
{
Id = id;
Level = level;
}
}
➡ Id/Level 초기화 코드가 3곳에 중복 → 유지보수 어려움
public class User
{
public string Id;
public int Level;
// 메인 생성자
public User(string id, int level)
{
Id = id;
Level = level;
}
public User() : this("guest", 1) { }
public User(string id) : this(id, 1) { }
}
➡ 공통 로직은 오직 하나의 메인 생성자에만 존재
➡ 나머지 생성자들은 this()로 연결
➡ 실무에서 가장 많이 쓰는 대표 패턴
필수값은 생성자로 강제하고,
선택적인 값은 Property로 설정하는 방식입니다.
public class Member
{
// 필수값
public string Id { get; }
public string Password { get; }
// 선택값
public string Email { get; set; }
public string Phone { get; set; }
public Member(string id, string password)
{
Id = id;
Password = password;
}
}
var m = new Member("hong", "1234")
{
Email = "hong@test.com",
Phone = "010-0000-0000"
};
➡ 필수값은 생성자로 강제
➡ 선택값은 Property로 후처리
➡ API/도메인 모델 설계에서 자주 쓰는 패턴
객체 생성 시 입력값이 잘못되지 않도록 메인 생성자에서 유효성 검사를 처리하고,
다른 생성자들은 this()로 연결하는 전략입니다.
public class Product
{
public string Name { get; }
public int Price { get; }
public Product(string name, int price)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("제품명은 필수입니다.");
if (price < 0)
throw new ArgumentException("가격은 0보다 커야 합니다.");
Name = name;
Price = price;
}
public Product(string name) : this(name, 0) { }
}
➡ 유효성 검사는 메인 생성자에서만
➡ 나머지 생성자는 this()로 연결하여 코드 중복 방지
예: 파일 객체
public class FileLoader
{
public FileLoader(string path) { }
public FileLoader(Stream stream) { }
public FileLoader(byte[] bytes) { }
}
게임 캐릭터 예시
public Character() : this("Unknown", 1) { }
public Character(string name) : this(name, 1) { }
public Character(string name, int level)
{
Name = name;
Level = level;
}
public Report(string title) : this(title, DateTime.Now) { }
public Report(string title, DateTime date)
{
Title = title;
Date = date;
}
public class Sample
{
private int _a;
private int _b;
private int _c;
// 메인 생성자
public Sample(int a, int b, int c)
{
_a = a;
_b = b;
_c = c;
}
public Sample(int a, int b) : this(a, b, 0) { }
public Sample(int a) : this(a, 0, 0) { }
public Sample() : this(0, 0, 0) { }
}