การอ่านอินพุตเป็นจำนวนเต็ม (Integer) ใน C#
เนื่องจาก Console.ReadLine() คืนค่าเป็นสตริงเสมอ จึงต้องแปลงเป็นตัวเลขด้วยเมธอดแปลงชนิดข้อมูล
วิธีแปลงที่แนะนำ
using System;
class Demo
{
static void Main()
{
Console.Write("ป้อนตัวเลข: ");
string input = Console.ReadLine();
// วิธีที่ 1: int.TryParse (แนะนำ - ปลอดภัย ไม่โยน Exception)
if (int.TryParse(input, out int number))
{
Console.WriteLine($"คุณป้อนตัวเลข: {number}");
}
else
{
Console.WriteLine("ข้อมูลที่ป้อนไม่ใช่ตัวเลขที่ถูกต้อง");
}
// วิธีที่ 2: Convert.ToInt32 (โยน Exception หากแปลงไม่ได้)
try
{
int num = Convert.ToInt32(input);
Console.WriteLine($"แปลงด้วย Convert.ToInt32: {num}");
}
catch (FormatException)
{
Console.WriteLine("รูปแบบตัวเลขไม่ถูกต้อง");
}
catch (OverflowException)
{
Console.WriteLine("ตัวเลขเกินขอบเขตของ int");
}
// วิธีที่ 3: int.Parse (คล้าย Convert.ToInt32 แต่ไม่รับ null ได้)
// int num = int.Parse(input);
}
}
เปรียบเทียบเมธอดแปลง
| เมธอด | คืนค่า | จัดการ Error | ประสิทธิภาพ |
|---|---|---|---|
int.TryParse | bool (สำเร็จ/ล้มเหลว) | ไม่โยน Exception | ดีที่สุด |
Convert.ToInt32 | int | โยน FormatException/OverflowException | ดี |
int.Parse | int | โยน FormatException/OverflowException/ArgumentNullException | ดี |
ตัวอย่างการใช้งานจริง
Console.Write("ป้อนอายุ: ");
string ageInput = Console.ReadLine();
if (int.TryParse(ageInput, out int age) && age > 0)
{
Console.WriteLine($"อายุ {age} ปี");
}
else
{
Console.WriteLine("กรุณาป้อนอายุเป็นตัวเลขบวก");
}
แนะนำ: ใช้ int.TryParse() สำหรับโปรแกรมจริง เพราะจัดการข้อผิดพลาดได้โดยไม่ต้องใช้ try-catch