Use the C# TryParse method to see if you can convert a string to a number.
In string processing, it is often desired to convert a string of written numbers into an int or long type that can perform numerical operations. Converting a numeric value to a string is not a problem, but the reverse is not possible and may return an exception, which must be checked to avoid an exception.
When to use the TryParse method
C#'s TryParse method can handle a variety of types, including double, long, int, and byte. Each of these methods checks to see if the argument can be converted to the target type and returns True if it can and False otherwise.
Attempting to convert to a type that cannot be converted will raise an exception, but the TryParse method simply returns False, so there is no need to catch further exceptions.
Because exception handling takes a lot of coding time and processing load, it is more effective to check whether the conversion can be done with TryParse before conversion.
How to use the TryParse method
When using the TryParse method, two arguments are specified. The string of the string type to be checked is placed in the first argument, and the variable of the type to be converted is placed in the second argument, but "out" is added before this second argument. If the conversion is successful, the converted number is entered into the variable of the second argument, so there is no need to bother checking and then converting again. If the conversion fails, 0 is assigned.
C# TryParse Example
using System; namespace CSharp_TryParse_Example { public class Program { public static void Main(string[] args) { string str1 = "120", str2 = "120.10", str3 = "s120"; int convertedInt1, convertedInt2, convertedInt3; //True Console.WriteLine("Conversion: {0}, converted value: {1}", int.TryParse(str1, out convertedInt1), convertedInt1); //False Console.WriteLine("Conversion: {0}, converted value: {1}", int.TryParse(str2, out convertedInt2), convertedInt2); //False Console.WriteLine("Conversion: {0}, converted value: {1}", int.TryParse(str3, out convertedInt3), convertedInt3); // string str4 = "120.30"; string str5 = "120.40"; double convertedDouble; float convertedFloat; //True Console.WriteLine("Conversion: {0}, converted value: {1}", double.TryParse(str4, out convertedDouble), convertedDouble); //True Console.WriteLine("Conversion: {0}, converted value: {1}", float.TryParse(str5, out convertedFloat), convertedFloat); } } }
Output:
Conversion: True, converted value: 120
Conversion: False, converted value: 0
Conversion: False, converted value: 0
Conversion: True, converted value: 120.3
Conversion: True, converted value: 120.4