ทั้งคู่แปลง String → Int32 แต่ต่างกันที่การจัดการ Null
Convert.ToInt32(null)
คืนค่า 0** ไม่ Throw Exception
string s = null; int result = Convert.ToInt32(s); // 0
int.Parse(null)
Throw ArgumentNullException
string s = null; int result = int.Parse(s); // Unhandled Exception: Value cannot be null.
ตัวอย่าง String ที่แปลงได้
string s = "5000"; int r1 = int.Parse(s); // 5000 int r2 = Convert.ToInt32(s); // 5000
สรุป
| Scenario | int.Parse | Convert.ToInt32 |
|---|---|---|
| Valid Number String | OK | OK |
| Null | ArgumentNullException | Return 0 |
| Invalid Format (e.g. "abc") | FormatException | FormatException |
| Overflow | OverflowException | OverflowException |
แนะนำ
- ใช้ int.TryParse สำหรับ Validation (Return bool + out int)
- ใช้ Convert.ToInt32 ถ้าอาจเป็น Null และต้องการ Default 0
- ใช้ int.Parse ถ้าแน่ใจว่า Not Null และ Valid Format