Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Default Constructor (Constructor mặc định) trong C#

Default Constructor là constructor không tham số (public ClassName()). Được compiler tự động tạo nếu class không định nghĩa constructor nào.

Đặc điểm

  • Không tham số.
  • Khởi tạo field với giá trị mặc định: 0 (numeric), null (reference), false (bool), \0 (char).
  • Gọi base constructor ngầm (base()).

Ví dụ: Default Constructor ngầm vs tường minh

using System;

public class Department
{
    public string Name { get; set; }
    public int EmployeeCount { get; set; }
    
    // Không viết constructor nào → Compiler tạo default constructor ngầm
    // public Department() { } // Tương đương
}

public class DepartmentExplicit
{
    public string Name { get; set; }
    public int EmployeeCount { get; set; }
    
    // Tường minh default constructor
    public DepartmentExplicit()
    {
        Console.WriteLine("Constructor Invoked");
        Name = "Unknown"; // Custom default
        EmployeeCount = 0;
    }
}

class Program
{
    static void Main()
    {
        // Default constructor ngầm
        Department d1 = new Department();
        Console.WriteLine($"d1: Name={d1.Name}, Count={d1.EmployeeCount}"); // null, 0
        
        // Default constructor tường minh
        DepartmentExplicit d2 = new DepartmentExplicit();
        Console.WriteLine($"d2: Name={d2.Name}, Count={d2.EmployeeCount}"); // Unknown, 0
    }
}

Kết quả

d1: Name=, Count=0
Constructor Invoked
d2: Name=Unknown, Count=0

Quy tắc quan trọng

Nếu bạn định nghĩa bất kỳ constructor nào (parameterized), default constructor sẽ KHÔNG được tạo tự động.
public class MyClass
{
    public MyClass(int x) { } // Có constructor có tham số
    
    // Không có default constructor ngầm!
}

// MyClass m = new MyClass(); // COMPILE ERROR: No parameterless constructor
MyClass m = new MyClass(5); // OK

Cách khôi phục default constructor

public class MyClass
{
    public MyClass(int x) { }
    
    // Phải khai báo tường minh nếu cần
    public MyClass() { } 
}

Struct: Luôn có default constructor

Struct không thể xóa default constructor. new MyStruct() luôn hợp lệ, khởi tạo tất cả field = 0/null.

struct Point
{
    public int X, Y;
    // Không thể viết: public Point() { } // Error trước C# 10
    // C# 10+: có thể có parameterless constructor
}

Point p = new Point(); // X=0, Y=0 - luôn OK

Best Practices

  • Luôn cung cấp default constructor nếu class dùng cho serialization (XML/JSON), reflection, Activator.CreateInstance, EF Core, Dapper...
  • Dùng required keyword (C# 11+) cho property bắt buộc set qua object initializer: public required string Name { get; set; }.
  • Tránh logic phức tạp trong constructor (khó test, exception handling). Dùng Factory method.