Convert String to Int in C# with Example – Programming, Pseudocode Example, C# Programming Example
C#

Convert String to Int in C# with Example

Converting a string to an int is one of the easiest things to do in C# and it’s also one of the most common. The .NET Framework provides a couple built in ways to convert a C# string to int, or several other numeric datatypes.

Convert Class

I had said that there are are couple of different ways you can do this. First and most populer way is the use of Convert Class. Convert class provides different methods to convert a base data type to another base data type. The base types supported by the Convert class are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String. It also provides methods that support other conversions.

Therefore that we can use Convert class for converting string to int or int to string.

Here is the example of Convert Class that use to convert string to int.

int.Parse & int.TryParse

There is the another way to the using of int.TryParse or int.Parse. This is one of the shortest ways of the using. In case of the string can’t be converted the int.Parse() throws an exceptions where as int.TryParse() return a bool value, false.

int.Parse: The int.Parse C# method works great if you’re sure that the conversion from string to an integer is going to be successful and error

 

int.TryParse: Another method you can use to convert strings to ints that does a better job of handling errors is by using the int.TryParse method.  When the following example fails to parse the string as a valid integer, you can see that we just set it to 0.

Conclusion

If you’re looking to convert a string to an integer, the int. The tryparse method is probably the right way to go.

 

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.