Archive
ข้อแตกต่างระหว่าง Int32.Parse(), Convert.ToInt32(), and Int32.TryParse()
การใช้งานการแปลงค่าข้อมูลจาก string ไปเป็นค่าอื่น ๆ เช่น Integer นั้นจะพบว่า มี method ให้เราใช้งานหลายตัว เราก็เลือกใช้ไปตามชอบแต่ทราบหรือไม่ครับว่า ข้อแตกต่างในการใช้งาน เป็นอย่างไร เราควรเลือกใช้อะไรดี มีคำตอบดี ดี ให้ดังนี้ ครับ Credit : http://www.codeproject.com/Articles/32885/Difference-Between-Int32-Parse-Convert-ToInt32-and Int32.Parse (string s) ใช้แปลง string ที่แสดงตัวเลข integer 32 bit signed
- ถ้าค่า s เป็น null จะ throw ArgumentNullException
- ถ้าค่า s เป็นค่าอื่น จะ throw FormatException
- ถ้า ค่า s เกิน MinValue และ MaxValue จะ throw OverflowException
ตัวอย่าง
string s1 = “1234”;
string s2 = “1234.65”;
string s3 = null; s
tring s4 = “123456789123456789123456789123456789123456789”;
int result;bool success;
result = Int32.Parse(s1);//– 1234
result = Int32.Parse(s2); //– FormatException
result = Int32.Parse(s3);//– ArgumentNullException
result = Int32.Parse(s4); //– OverflowException
Convert.ToInt32(string s) ใช้แปลง string ที่แสดงตัวเลข integer 32 bit signed ให้เป็นตัวเลข
- ถ้าค่า s เป็น null จะ ได้ค่าเป็น 0
- ถ้าค่า s เป็นค่าอื่น จะ throw FormatException
- ถ้าค่า s เกิน MinValue และ MaxValue จะ throw OverflowException
result = Convert.ToInt32(s1); //– 1234
result = Convert.ToInt32(s2);//– FormatException
result = Convert.ToInt32(s3);//– 0
result = Convert.ToInt32(s4); //– OverflowException
Int32.TypParse(string s,out int) ใช้แปลง ค่า string ที่แทนตัวเลข integer 32 bit ให้กับ out variable และ return true ถ้าแปลงได้ และ false ถ้าแปลงไม่ได้
- ถ้าค่า s เป็น null out จะ ได้ค่าเป็น 0
- ถ้าค่า s เป็นค่าอื่น จะให้ค่า out เป็น 0
- ถ้าค่า s เกิน MinValue และ MaxValue จะ ให้ค่า out เป็น 0
success = Int32.TryParse(s1, out result); //– success = true; result => 1234
success = Int32.TryParse(s2, out result); //– success = false; result => 0
success = Int32.TryParse(s3, out result); //– success = false; result => 0
success = Int32.TryParse(s4, out result); //– success => false; result => 0
กล่าวโดยสรุป Convert.ToInt32 ดีกว่า Int32.Parse เพราะ ให้ค่า 0 แทนการ throw exception แต่การใช้งานนั้นก็สามารถเลือกใช้ตามความเหมาะสมนะครับ TypeParse อาจจะเป็นตัวเลือกที่ดีที่สุด เพราะ ตัวมันเองจัดการกับ exception หมดแล้ว Credit : http://www.codeproject.com/Articles/32885/Difference-Between-Int32-Parse-Convert-ToInt32-and