Convert.ToInt32() chuyển đổi chuỗi hoặc giá trị khác thành số nguyên 32-bit signed (int). Xử lý an toàn null (trả về 0).
Ví dụ minh họa
using System;
class Program
{
static void Main()
{
string str = "12";
Console.WriteLine("Chuỗi: " + str);
int n = Convert.ToInt32(str);
Console.WriteLine("Số: " + n);
}
}
Kết quả đầu ra
Chuỗi: 12 Số: 12
So sánh:
int.Parse(): ném ngoại lệ nếu null hoặc format saiConvert.ToInt32(): null → 0, format sai → ném FormatExceptionint.TryParse(): an toàn nhất, trả về bool, không ném ngoại lệ