เมื่อใช้ประเภท DateTime nullable คุณสามารถกำหนด Null literal ให้กับประเภท DateTime ได้
DateTime ที่เป็นค่าว่างถูกระบุโดยใช้ไวยากรณ์เครื่องหมายคำถามต่อไปนี้
DateTime?
ต่อไปนี้เป็นรหัสสำหรับใช้งาน Nullable Datetime
ตัวอย่าง
using System;
class Program {
static void Main() {
DateTime? dt = null;
DateFunc(dt);
dt = DateTime.Now;
DateFunc(dt);
dt = null;
Console.WriteLine(dt.GetValueOrDefault());
}
static void DateFunc(DateTime? dt) {
if (dt.HasValue) {
Console.WriteLine(dt.Value);
} else {
Console.WriteLine(0);
}
}
} ผลลัพธ์
0 9/17/2018 8:27:07 AM 1/1/0001 12:00:00 AM