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

Optional Property ใน C# Class

ใน C# ไม่มีคีย์เวิร์ด optional สำหรับ Property โดยตรง แต่สามารถทำให้ Property เป็น "Optional" ได้หลายวิธี

วิธีที่ 1: Nullable Reference Types (C# 8+) — แนะนำ

#nullable enable

public class Employee {
    public string Name { get; set; }           // Required (non-nullable)
    public string? MiddleName { get; set; }    // Optional (nullable)
    public string? NickName { get; set; }      // Optional
}

Compiler จะเตือนถ้าพยายาม assign null ให้ Non-nullable property

วิธีที่ 2: Default Value

public class Settings {
    public int TimeoutSeconds { get; set; } = 30;     // Default 30
    public string LogLevel { get; set; } = "Info";    // Default "Info"
    public bool EnableCache { get; set; } = true;     // Default true
}

วิธีที่ 3: Custom Attribute (สำหรับ Framework/Serialization)

ใช้เมื่อต้องการ Metadata สำหรับ JSON Serializer, ORM, Validation ฯลฯ

[AttributeUsage(AttributeTargets.Property)]
public class OptionalAttribute : Attribute { }

public class Employee {
    public string EmpName { get; set; }        // Required
    [Optional]
    public string AlternativeName { get; set; } // Optional (metadata only)
}

หมายเหตุ: Attribute นี้เป็น Metadata เท่านั้น Compiler ไม่บังคับ — ต้องมี Logic/Framework อ่าน Attribute นี้

วิธีที่ 4: Init-only Properties (C# 9+)

public class Person {
    public string FirstName { get; init; }  // ตั้งค่าได้ตอน init/constructor เท่านั้น
    public string LastName { get; init; }
    public string? MiddleName { get; init; } // Optional
}

ตัวอย่างครบถ้วน (Modern C#)

#nullable enable
using System.Text.Json.Serialization;

public class ApiRequest {
    // Required
    public string UserId { get; init; } = string.Empty;
    public string Action { get; init; } = string.Empty;
    
    // Optional with default
    public int Page { get; init; } = 1;
    public int PageSize { get; init; } = 20;
    
    // Truly optional (nullable)
    public string? Filter { get; init; }
    public DateTime? FromDate { get; init; }
    public DateTime? ToDate { get; init; }
    
    // For JSON: ignore null khi serialize
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? CorrelationId { get; init; }
}

สรุปแนวทางเลือก

สถานการณ์แนะนำ
General C# ClassNullable Reference Types (string?) + Default Values
DTO / API ModelNullable + JsonIgnore + init
Entity FrameworkNullable + Fluent API .IsRequired(false)
Custom FrameworkCustom Attribute + Reflection