How can we convert a string to an integer in C#?
In C#, you can use the int.Parse() method or the int.TryParse() method to convert a string type to an int type.
- Utilize the int.Parse() method:
string str = "123";
int num = int.Parse(str);
- Utilize the int.TryParse() method:
string str = "123";
bool success = int.TryParse(str, out int num);
if (success)
{
// 转换成功,num为转换后的int类型值
}
else
{
// 转换失败,处理转换失败的逻辑
}
It is important to note that if a string cannot be properly converted to an int type, the int.Parse() method will throw a FormatException exception, while the int.TryParse() method will return false and set the output parameter to 0.