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

Constructor có tham số (Parameterized Constructor) trong C#

Parameterized Constructor là constructor nhận một hoặc nhiều tham số, cho phép khởi tạo đối tượng với giá trị ban đầu tùy chỉnh. Khác với default constructor (không tham số).

Cú pháp

public TenClass(Kieu1 param1, Kieu2 param2, ...)
{
    // Khởi tạo field/property từ tham số
    this.Field = param1;
}

Ví dụ: Lớp Line (Đoạn thẳng)

using System;

namespace Demo
{
    class Line
    {
        private double length; // Field private
        
        // Parameterized constructor
        public Line(double len)
        {
            Console.WriteLine($"Object được tạo, length = {len}");
            length = len; // Gán giá trị
        }
        
        // Property (C# 6+ expression body)
        public double Length 
        { 
            get => length; 
            set => length = value > 0 ? value : 0; // Validation
        }
        
        // Method
        public void Display() => Console.WriteLine($"Length: {length}");
    }
    
    class Program
    {
        static void Main()
        {
            // Tạo object với constructor có tham số
            Line line = new Line(10.0);
            line.Display(); // Length: 10
            
            // Thay đổi qua property
            line.Length = 6.0;
            line.Display(); // Length: 6
            
            // Validation trong setter
            line.Length = -5; // Sẽ set thành 0
            line.Display(); // Length: 0
            
            Console.ReadKey();
        }
    }
}

Kết quả

Object được tạo, length = 10
Length: 10
Length: 6
Length: 0

Constructor Overloading (Nạp chồng Constructor)

Một class có thể có nhiều constructor với signature khác nhau:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
    
    // Default constructor
    public Point() : this(0, 0) { } // Gọi constructor khác
    
    // Parameterized constructor
    public Point(int x, int y)
    {
        X = x; Y = y;
    }
    
    // Copy constructor
    public Point(Point other)
    {
        X = other.X;
        Y = other.Y;
    }
    
    // Constructor từ tuple (C# 7+)
    public Point((int X, int Y) tuple) : this(tuple.X, tuple.Y) { }
}

Best Practices

  1. Constructor chaining: Dùng this(...) để gọi constructor khác, tránh lặp code.
  2. Validation: Kiểm tra tham số trong constructor, ném ArgumentException nếu invalid.
  3. Readonly fields: Gán trong constructor, không thể thay đổi sau: private readonly int id;.
  4. Dependency Injection: Constructor injection cho services.
  5. Record types (C# 9+): Tự động generate constructor cho positional records: record Person(string Name, int Age);.

Lưu ý

  • Nếu định nghĩa bất kỳ constructor nào, compiler KHÔNG tạo default constructor (parameterless) tự động.
  • Struct: Luôn có default constructor ngầm (không thể xóa), gán 0/null cho mọi field. Không thể định nghĩa parameterless constructor cho struct (trừ C# 10+ struct có thể).
  • Expression-bodied constructor (C# 7+): public Line(double len) => length = len;.