Different ways to convert String to Integer in C#
Like other programming languages, in C# we can convert string to int. There are three ways to convert it and they are as follows:
- Using the Parse Method
- Using the TryParse Method
- Using the Convert Method from (System.Convert class)
The input string can be anything like “10”, “10.10”, “10GeeksforGeeks”, “” (Your string can be number, a combination of characters or an Empty String).
When a given string is number or floating-point number then we can use directly any of above-listed methods to convert it from string to int but the combination of characters and an empty string will throw an error which needs to catch using exceptional handling.
1. Using the Parse Method
Here, we are calculating the area of a circle but the given input length is in string format and hence used Int32.Parse() method to convert the length from string to int (32-bit signed integer equivalent).
Area of a circle is: 100
When we have a value greater than Integer: If you assign the value big value to string then it will through an OverflowException as int data type can’t handle the large values (It very much depends upon the range of data types).
The output will be
System.OverflowException: Value was either too large or too small for an Int32.
When we have Empty String: If you keep string blank then it will through an exception System Format Exception as the input is blank.
The output will be: System.FormatException: Input string was not in a correct format.
2. Using the TryParse Method
Here, we have used TryParse() method, the difference in Parse() and TryParse() method is only that TryParse() method always return the value it will never throw an exception. If you closely look at the value of an input, then it clearly shows that it will throw an exception but TryParse() will never throw an exception. Hence the output is Zero.
Area of a circle is: 0
3. Using the Convert Method
Here, we have used Convert.ToInt32() method, the difference in Parse() and Convert.ToInt32() method is only that Convert.ToInt32() method always accept the null value return it. Hence the output is Zero. We have used exceptional handling in this example so, try block will throw the exception if occurred and catch block will accept the exception and write whatever exception occurred.
Area of a circle is: 0