There are three easiest ways which allow you to convert string data type to int:
- Parse method
- TryParse method
- Convert class
In the following article I’ll explain each one and show the example of its usage.
Parse method
Basic form of Parse method receives string as an input parameter and returns converted value as an integer data type. In case the format of input value is not able to be converted, an exception is being thrown.
Parse method is overloaded and contains two more parameters which can be optionally passed:
- number style which defines allowed input string format (e.g. allows currency symbol, decimal point etc.).
- format provider which defines culture-specific format
Above example shows converting to int type which is equivalent to Int32. You can also use following forms depending on your needs.
TryParse method
TryParse method is very similar to Parse with the difference that it returns true or false (depending on the success or failure during conversion) and a result of conversion is available through output parameter.
The simplest form of TryParse has two parameters: string to be converted and output parameter which is the conversion result. Similar as Parse, there are overloads which allow to define number style and format provider.
It is worth noticing that TryParse returns false instead of throwing exception in the situation when conversion fails.
Convert class
Convert is a static class where one of the exposed methods is ToInt32. It is a function which allows to convert various types (including string) to integer. Internally it uses Parse method which was described above, as a result of what it behaves in a similar way: returns converted value and throws exception in case of failure.
If you would like to receive Int16 or Int64 you can use accordingly ToInt16 or ToInt64 methods.
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW