How to convert a C# string to a number?

In C#, you can convert a string to a number using methods such as int.Parse, Convert.ToInt32, or int.TryParse.

  1. Converts a string representation of a number to an integer.
string str = "123";
int num = int.Parse(str);
  1. Change to an integer.
string str = "456";
int num = Convert.ToInt32(str);
  1. Attempt to convert a string to an integer and determine if the conversion was successful.
string str = "789";
int num;
if (int.TryParse(str, out num))
{
    // 转化成功
}
bannerAds