หมวดหมู่: C#/.NET

C# OOP Modern Features: Classes, Records, Pattern Matching & Primary ConstructorsC# OOP Modern Features: Classes, Records, Pattern Matching & Primary Constructors

การเขียนโปรแกรมเชิงวัตถุ (Object-Oriented Programming: OOP) ในภาษา C# มีวิวัฒนาการไปอย่างก้าวกระโดดในเวอร์ชันใหม่ๆ (ตั้งแต่ C# 9 จนถึง C# 12/13+) จากเดิมที่ต้องเขียนโค้ดซ้ำซ้อน (Boilerplate code) จำนวนมากเพื่อสร้าง Class, Constructor หรือตรวจสอบ Type ปัจจุบัน C# ได้นำแนวคิดจาก Functional Programming มาผสมผสาน ทำให้ OOP มีความกระชับ ปลอดภัย และอ่านง่ายขึ้นกว่าเดิมมาก

บทความนี้จะพาไปเจาะลึก 4 ฟีเจอร์สำคัญที่เปลี่ยนโฉมการเขียน C# OOP ให้ทันสมัยและทรงพลังยิ่งขึ้น


Primary Constructors: ลดความซ้ำซ้อนในการสร้าง Class

ในอดีต การประกาศ Class ที่รับค่า Dependency หรือ Property เริ่มต้น ต้องเขียนทั้ง Field, Constructor และ Assignment ทำให้โค้ดดูยาวเกินความจำเป็น ตั้งแต่ C# 12 เป็นต้นมา เราสามารถใช้ Primary Constructors กับ class และ struct ได้โดยตรง (จากเดิมที่ใช้ได้เฉพาะใน record)


แบบดั้งเดิม (Traditional Class)

C#

public class OrderService
{
    private readonly IOrderRepository _repository;
    private readonly ILogger _logger;

    public OrderService(IOrderRepository repository, ILogger logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public void Process(int orderId)
    {
        _logger.Log($"Processing {orderId}");
        _repository.Save(orderId);
    }
}

แบบ Modern (Primary Constructor)

C#

public class OrderService(IOrderRepository repository, ILogger logger)
{
    public void Process(int orderId)
    {
        logger.Log($"Processing {orderId}");
        repository.Save(orderId);
    }
}

จุดเด่น
พารามิเตอร์ repository และ logger จะอยู่ใน Scope ของทั้ง Class ทันที ช่วยลดโค้ดได้เกือบครึ่ง เหมาะอย่างยิ่งสำหรับการทำ Dependency Injection (DI)


Records: โครงสร้างข้อมูลแบบ Immutable ที่เกิดมาเพื่อ Data

หากคุณต้องการสร้าง Model หรือ DTO (Data Transfer Object) ที่เน้นการเก็บข้อมูลและไม่ต้องการให้แก้ไขค่าได้ภายหลัง (Immutability) การใช้ class ปกติอาจไม่ตอบโจทย์เท่า record (เปิดตัวใน C# 9 และเพิ่ม record struct ใน C# 10)

C#

// ประกาศเพียงบรรทัดเดียว ได้ทั้ง Constructor, Properties, Equals, GetHashCode และ ToString()
public record Customer(string Id, string Name, string Tier);

ความสามารถที่เหนือกว่า Class ทั่วไป

  1. Value-based Equality
    เปรียบเทียบความเท่ากันจาก “ค่าข้างใน” ไม่ใช่ Reference ใน Memory
    C#
    var c1 = new Customer("001", "Somchai", "Gold");
    var c2 = new Customer("001", "Somchai", "Gold");
    Console.WriteLine(c1 == c2); // True (ถ้าเป็น class จะได้ False)
  2. Non-destructive Mutation (with expression)
    สร้าง Object ใหม่โดยคัดลอกค่าเดิมและเปลี่ยนเฉพาะบาง Field
    C#
    var upgradedCustomer = c1 with { Tier = "Platinum" };

Pattern Matching: บอกลา if-else และ Type Casting แบบเดิม ๆ

Pattern Matching ใน C# ถูกพัฒนาให้ฉลาดขึ้นเรื่อยๆ ทำให้เราสามารถตรวจสอบทั้ง ชนิดของข้อมูล (Type) และ เงื่อนไขของคุณสมบัติ (Property) ไปพร้อมกันได้อย่างสวยงาม

C#

public abstract record Payment;
public record CashPayment(decimal Amount) : Payment;
public record CreditCardPayment(decimal Amount, string CardType, int Installments) : Payment;
public record CryptoPayment(decimal Amount, string Coin) : Payment;

public static decimal CalculateFee(Payment payment) => payment switch
{
    // ตรวจสอบ Type พร้อมดึงค่าออกมาใช้งาน (Declaration Pattern)
    CashPayment => 0m,

    // Property Pattern + Relational Pattern
    CreditCardPayment { CardType: "VIP", Amount: > 10000 } => 0m,
    CreditCardPayment { Installments: > 3 } card => card.Amount * 0.03m,
    CreditCardPayment card => card.Amount * 0.015m,

    // List / String matching หรือเงื่อนไขซับซ้อน
    CryptoPayment { Coin: "BTC" or "ETH" } crypto => crypto.Amount * 0.01m,

    // Fallback
    null => throw new ArgumentNullException(nameof(payment)),
    _ => throw new NotSupportedException("Unsupported payment method")
};

จุดเด่น
คอมไพเลอร์จะช่วยตรวจสอบให้ด้วยว่าเราเขียนเงื่อนไขครอบคลุมทุกกรณี (Exhaustiveness) หรือยัง ลดโอกาสเกิด Bug จากการลืมดักเงื่อนไข


เลือกใช้อะไรดีระหว่าง class และ record?

คุณสมบัติclass (Modern)record (record class)
จุดประสงค์หลักObject ที่มีพฤติกรรมซับซ้อน (Behavior & State)Object ที่เน้นการเก็บและส่งต่อข้อมูล (Data & DTOs)
การเปลี่ยนแปลงค่า (Mutability)เปลี่ยนแปลงค่าได้ตามปกติ (Mutable)เน้นไม่เปลี่ยนแปลงค่า (Immutable by default)
การเปรียบเทียบ (==)เทียบจาก Reference (ที่อยู่ใน Memory)เทียบจาก Value (ค่าของ Property ทุกตัว)
Primary Constructorรองรับ (พารามิเตอร์เป็น Private state)รองรับ (พารามิเตอร์กลายเป็น Public init properties อัตโนมัติ)
การคัดลอกข้อมูล (with)ไม่รองรับโดยตรงรองรับผ่าน with expression

ตัวอย่างการนำทั้งหมดมาประกอบร่างกัน

เมื่อนำทั้ง Primary Constructors, Records และ Pattern Matching มาใช้งานร่วมกันในสถาปัตยกรรมจริง จะได้โค้ดที่กระชับและสื่อความหมายได้ชัดเจนระดับ Self-documenting code

C#

// 1. ใช้ Record แทน State/Events
public record Order(string Id, decimal TotalAmount, bool IsMember);

// 2. ใช้ Primary Constructor สำหรับ Service
public class DiscountCalculator(decimal memberDiscountRate)
{
    // 3. ใช้ Switch Expression + Pattern Matching จัดการ Logic
    public decimal GetFinalPrice(Order order) => order switch
    {
        { TotalAmount: <= 0 } => 0m,
        { IsMember: true, TotalAmount: >= 1000 } => order.TotalAmount * (1 - memberDiscountRate - 0.05m),
        { IsMember: true } => order.TotalAmount * (1 - memberDiscountRate),
        _ => order.TotalAmount
    };
}

การอัปเกรดสไตล์การเขียน C# OOP ให้เป็นแบบ Modern ไม่ใช่แค่เรื่องของความสวยงามทางไวยากรณ์ (Syntactic Sugar) แต่ช่วยลดความผิดพลาดจากการจัดการ State, ลดโค้ดขยะ และทำให้ทีมพัฒนาสามารถอ่านและดูแลรักษาโค้ดในระยะยาวได้ง่ายขึ้นอย่างเห็นได้ชัด