Nullable Types อนุญาตให้ Value Type (ปกติไม่สามารถเป็น null ได้) รับค่า null ได้ โดยใช้ ? Suffix หรือ Nullable<T>
Syntax
int? num1 = null; // Skipped syntax Nullable<int> num2 = null; // Full syntax
ตัวอย่างครบถ้วน
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double?(); // null
double? num4 = 3.14157;
bool? boolVal = new bool?(); // null
Console.WriteLine("Nullables: {0}, {1}, {2}, {3}", num1, num2, num3, num4);
Console.WriteLine("Nullable bool: {0}", boolVal);
// ตรวจสอบ HasValue
Console.WriteLine("num1.HasValue: " + num1.HasValue); // False
Console.WriteLine("num2.HasValue: " + num2.HasValue); // True
// ดึงค่าอย่างปลอดภัย
Console.WriteLine("num1.GetValueOrDefault(): " + num1.GetValueOrDefault()); // 0
Console.WriteLine("num1.GetValueOrDefault(-1): " + num1.GetValueOrDefault(-1)); // -1
// Null-coalescing operator ??
int value = num1 ?? -1; // ถ้า null ให้ -1
Console.WriteLine("num1 ?? -1 = " + value);
Console.ReadLine();
}
}
}
ผลลัพธ์
Nullables: , 45, , 3.14157 Nullable bool: num1.HasValue: False num2.HasValue: True num1.GetValueOrDefault(): 0 num1.GetValueOrDefault(-1): -1 num1 ?? -1 = -1
คุณสมบัติสำคัญ
HasValue- true ถ้ามีค่า, false ถ้า nullValue- ดึงค่า (โยน Exception ถ้า null)GetValueOrDefault()- ดึงค่าหรือค่าเริ่มต้น (0/false)GetValueOrDefault(T)- ดึงค่าหรือค่าที่กำหนด- Operator
??(Null-coalescing) ใช้ร่วมได้สะดวก
ข้อจำกัด
- ใช้กับ Value Type เท่านั้น (struct, enum, primitive)
- Reference Type (class, string, array) เป็น Nullable อยู่แล้ว
- Nested Nullable ไม่ได้:
int??❌