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

วิธีให้ Auto-Property มี Default Value ใน C#

Auto-Property คืออะไร?

Property ที่ Compiler สร้าง Backing Field ให้อัตโนมัติ Syntax: public Type Name { get; set; }

วิธีตั้ง Default Value

1. C# 6.0+ Property Initializer (แนะนำ)


public class Demo
{
    // Inline Initializer - สะดวก อ่านง่าย
    public string FirstName { get; set; } = "Default Name";
    public int Age { get; set; } = 25;
    public List<string> Tags { get; set; } = new List<string>();
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

2. Constructor (C# 5.0 และก่อน / Complex Logic)


public class Demo
{
    public string FirstName { get; set; }
    public int Age { get; set; }
    
    public Demo()
    {
        FirstName = "Default Name";
        Age = 25;
        // Complex Logic ได้: Random, Config, Dependency Injection
    }
}

ตัวอย่างเปรียบเทียบ


using System;

class DemoOldWay // C# 5.0 Style
{
    public DemoOldWay()
    {
        FirstName = "DemoName";
    }
    public string FirstName { get; set; }
}

class DemoNewWay // C# 6.0+ Style
{
    public string FirstName { get; set; } = "DemoName";
}

class Program
{
    static void Main()
    {
        var old = new DemoOldWay();
        var @new = new DemoNewWay();
        
        Console.WriteLine($"Old: {old.FirstName}");
        Console.WriteLine($"New: {@new.FirstName}");
        Console.ReadLine();
    }
}

Output

Old: DemoName
New: DemoName

Init-Only Properties (C# 9+) - Immutable หลัง Init


public class Person
{
    // ตั้งค่าได้ตอน Create/Object Initializer เท่านั้น
    public required string Name { get; init; } = "Unknown";
    public int Age { get; init; } = 0;
    
    // Computed Property
    public string DisplayName => $"{Name} ({Age})";
}

// Usage
var p1 = new Person { Name = "John", Age = 30 };
// p1.Name = "Jane"; // ❌ Compile Error - init only
var p2 = new Person(); // ใช้ Default Values

Required Properties (C# 11+) - บังคับ Initialize


public class User
{
    public required string Email { get; set; }
    public required string Password { get; init; }
    public string DisplayName { get; set; } = "Guest"; // Optional with Default
}

// Compiler Error ถ้าไม่ Set Required Properties
var user = new User { Email = "a@b.com", Password = "123" }; // OK
// var bad = new User(); // ❌ Error: Required members 'Email', 'Password' not set

Default Value สำหรับ Reference Types


// ❌ Dangerous: Shared Reference (Mutable Object)
public List<string> BadTags { get; set; } = new List<string>();

// ✅ Safe: Factory Method / Lambda (C# 10+)
public List<string> GoodTags { get; set; } = new(); // new() = new List()

// หรือใช้ Expression Body (C# 6+)
private List<string> _tags = new();
public List<string> Tags 
{ 
    get => _tags; 
    init => _tags = value ?? new(); 
}

สรุปแนะนำ

Scenarioแนะนำ
Simple Constant/DefaultProperty Initializer = value
Complex Logic / DIConstructor
Immutable After Creationinit Accessor (C# 9+)
Mandatory Fieldsrequired (C# 11+)
Mutable CollectionInitialize ใน Constructor หรือ ใช้ init + Factory