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.

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

CONS

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

CONS

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.