We often need to convert a string representation of numbers to integers. But there are a couple of ways to do the conversion, and which one is the safest approach? Let us try to understand all the different ways of conversion and find the safest of all.
How many ways to convert the string representation of numbers to Integer?
There are 3 ways to convert the string representation of numbers to Integer.
1. Convert
We can convert a string to an integer using different methods of the static convert class.
- Convert.Int16()
- Convert.Int32()
- Convert.Int64()
Let us understand with an example depicted below.
OUTPUT
In the output only the 1st and 4th case has passed. The other cases failed to convert the value to int number and also threw an exception while converting the value to int number.
1 & 4.
2.
3.
2. Parse()
Let us understand with an example depicted below.
OUTPUT
In the output only the 1st case has passed and all the other cases, 2nd, 3rd, and 4th, have failed to convert the value to int number and also threw an exception while converting the value to int number.
1.
2.
3.
4.
PROS
- It converts a valid numeric string to an integer value.
- Supports a different number of styles.
- Supports culture-specific custom formats.
CONS
- The number in the string must be within the range of int type on which the method is called.
- Throws exception on converting null or invalid numeric string.
3. TryParse()
Let us understand with an example depicted below.
OUTPUT
From the example you can notice clearly that the program has not thrown any exception and instead it has handled it very well by returning boolean as false and converting number to 0.
PROS
- It can convert different numeric strings, numeric styles, and culture-specific numeric strings to integers.
- It never throws an exception. Returns false if cannot parse to an integer.
CONS
- It must use out parameter.
Conclusion
So, after seeing all the examples we can conclude that using TryParse() method is the safest approach for converting string value to int number.