Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Constructors ใน C#: พื้นฐาน

Constructor ใน C# เป็นเมธอดพิเศษที่เรียกอัตโนมัติเมื่อสร้าง Instance ของคลาส (new ClassName()) ใช้สำหรับ Initialize Object State

ลักษณะสำคัญ

  • ชื่อเดียวกับ Class
  • ไม่มี Return Type (แม้ void)
  • สามารถ Overload ได้ (หลาย Constructor ต่าง Parameter)
  • สามารถมี Access Modifier: public, private, protected, internal

ตัวอย่างพื้นฐาน

using System;

public class Department
{
    // Constructor
    public Department()
    {
        Console.WriteLine("Constructor Invoked");
    }
    
    public static void Main(string[] args)
    {
        Department dept1 = new Department(); // Constructor เรียกที่นี่
    }
}

ผลลัพธ์

Constructor Invoked

ประเภท Constructor

ประเภทคำอธิบาย
Default / Parameterlessไม่มี Parameter (public ClassName())
Parameterizedมี Parameter สำหรับ Initialize
Staticstatic ClassName() - รันครั้งเดียว Init Static Fields
PrivatePrivate Constructor - ใช้ Singleton/Factory
Copy Constructorรับ Instance เดียวกัน Copy ค่า (C# ไม่มี Built-in ต้องเขียนเอง)

Constructor Chaining

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Person() : this("Unknown", 0) { }           // เรียก Constructor อื่นในคลาสเดียวกัน
    public Person(string name) : this(name, 0) { }     // Chaining
    public Person(string name, int age)                // Primary Constructor
    {
        Name = name;
        Age = age;
    }
}

Primary Constructors (C# 12+)

// Record Style
public record Person(string Name, int Age);

// Class Style (C# 12)
public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
}

Best Practices

  • ทำ Constructor ให้ Simple - Initialize Fields เท่านั้น
  • Validation ใน Constructor (Throw Exception หาก Invalid)
  • ใช้ readonly Fields กับ Constructor Injection
  • หลีกเลี่ยงการเรียก Virtual Methods ใน Constructor