Checked และ Unchecked Context ใน C#
C# อนุญาตให้ควบคุมการตรวจสอบล้น (overflow checking) สำหรับการดำเนินการคณิตศาสตร์จำนวนเต็ม (integral-type) ได้ 2 แบบ
Checked Context (ตรวจสอบล้น)
- โยน
OverflowExceptionเมื่อผลลัพธ์เกินขอบเขตของชนิดข้อมูล - เปิดใช้ได้ 3 ทาง: compiler option, คอนฟิก environment, keyword
checked - เป็นค่าเริ่มต้นในบางการตั้งค่าคอมไพเลอร์ (project settings)
int max = int.MaxValue; // 2,147,483,647
// ใช้ checked block
checked
{
int result = max + 1; // โยน OverflowException
}
// หรือ checked expression
int result = checked(max + 1); // โยน OverflowException
Unchecked Context (ไม่ตรวจสอบล้น)
- ตัดบิตที่ล้นออกไป (wrap around) ไม่โยน Exception
- เร็วกว่าเล็กน้อย เพราะไม่มีการตรวจสอบ
- ใช้ keyword
unchecked
int max = int.MaxValue; // 2,147,483,647
// ใช้ unchecked block
unchecked
{
int result = max + 1; // ผลลัพธ์: -2,147,483,648 (wrap around)
Console.WriteLine(result); // -2147483648
}
// หรือ unchecked expression
int result = unchecked(max + 1); // -2147483648
ตัวอย่างเปรียบเทียบ
using System;
class Demo
{
static void Main()
{
int val = 2147483647; // int.MaxValue
Console.WriteLine($"ค่าเริ่มต้น: {val}");
// Checked - จะโยน Exception
try
{
int checkedResult = checked(val + 10);
Console.WriteLine($"Checked: {checkedResult}");
}
catch (OverflowException ex)
{
Console.WriteLine($"Checked: โยน OverflowException - {ex.Message}");
}
// Unchecked - จะ wrap around
int uncheckedResult = unchecked(val + 10);
Console.WriteLine($"Unchecked: {uncheckedResult}"); // -2147483639
}
}
ผลลัพธ์
ค่าเริ่มต้น: 2147483647
Checked: โยน OverflowException - Arithmetic operation resulted in an overflow.
Unchecked: -2147483639
เมื่อไหร่ควรใช้แต่ละแบบ?
| สถานการณ์ | แนะนำ | เหตุผล |
|---|---|---|
| คำนวณทางการเงิน/บัญชี | checked | ความถูกต้องสำคัญ ไม่อนุญาตให้ผิดพลาดเงียบๆ |
| อัลกอริทึม Hash/Checksum | unchecked | ต้องการ wrap-around behavior |
| Game/Physics simulation | unchecked | ประสิทธิภาพสำคัญ ผลลัพธ์ประมาณได้ |
| General purpose | checked (default) | ปลอดภัย ค้นพบ bug ได้เร็ว |
การตั้งค่าระดับโปรเจกต์
ใน Project Properties → Build → Advanced → "Check for arithmetic overflow/underflow" ทำให้โค้ดทั้งโปรเจกต์เป็น checked โดยไม่ต้องเขียน keyword
ข้อจำกัด
- ใช้ได้กับ integral types เท่านั้น (int, long, byte, short, etc.)
- ไม่มีผลกับ floating-point (float, double) - พวกนี้เป็น Infinity ตาม IEEE 754
- ไม่มีผลกับ decimal (มีการตรวจสอบล้นในตัวเสมอ)