What is the usage of TryParse in C#?
In C#, the TryParse method is used to convert a string into a specific data type without throwing an exception. Its syntax is as follows:
bool TryParse(string s, out T result)
In this case, s is the string to be converted, T is the target data type, and result is the converted result. The TryParse method attempts to convert the string s to the target data type T and stores the result in result. If the conversion is successful, it returns true; if the conversion fails, it returns false and the default value of the target data type is stored in result.
Here is an example of the TryParse method:
string str = "123";
int number;
if (int.TryParse(str, out number))
{
Console.WriteLine("转换成功,结果为:" + number);
}
else
{
Console.WriteLine("转换失败");
}
In the example above, the TryParse method converts the string “123” to the integer type int and stores the result in number. If the conversion is successful, the output will be 123; if the conversion fails, the output will be conversion failed.