Chuỗi: string str = "9999";
Dùng Int32.Parse hoặc int.Parse:
int n = Int32.Parse(str);
Ví dụ
using System;
class Demo
{
static void Main()
{
string str = "9999";
int n = Int32.Parse(str);
Console.WriteLine(n);
}
}
Các cách chuyển đổi
| Method | Exception nếu fail | Ghi chú |
|---|---|---|
| int.Parse | FormatException, OverflowException | Nhanh, cho input tin cậy |
| int.TryParse | Không (trả bool) | An toàn, khuyến nghị |
| Convert.ToInt32 | FormatException, OverflowException | Xử lý null -> 0 |
TryParse pattern (khuyến nghị)
if (int.TryParse(str, out int n))
Console.WriteLine($"Parsed: {n}");
else
Console.WriteLine("Không phải số nguyên hợp lệ");
NumberStyles: int.Parse("1,234", NumberStyles.AllowThousands) cho phép dấu phẩy.