Convert a string to an integer in C#
This post will discuss how to convert a string to equivalent integer representation in C#.
1. Using Int32.Parse() method
To convert the string representation of a number to its 32-bit signed integer equivalent, use the Int32.Parse() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { string str = "100"; int x = Int32.Parse(str); // or, use `int.Parse()` Console.WriteLine(x); } } |
The Int32.Parse() method throws a FormatException if the string is not numeric. We can handle this with a try-catch block.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { string str = "100"; try { int x = Int32.Parse(str); Console.WriteLine(x); } catch (FormatException) { Console.WriteLine("Input string is invalid."); } } } |
2. Using Int32.TryParse() method
A better alternative is to call the Int32.TryParse() method. It does not throw an exception if the conversion fails. If the conversion is failed, this method simply returns false.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void Main() { string str = "100"; bool success = Int32.TryParse(str, out int x); // or, use `int.TryParse()` if (success) { Console.WriteLine(x); } else { Console.WriteLine("Input string is invalid."); } } } |
3. Using Convert.ToInt32() method
The Convert.ToInt32 method can be used to convert a specified value to a 32-bit signed integer.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { string str = "10s"; int x = Convert.ToInt32(str); Console.WriteLine(x); } } |
This method throws a FormatException if the string is not numeric. This can be handled using a try-catch block.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { string str = "100"; try { int x = Convert.ToInt32(str); Console.WriteLine(x); } catch (FormatException) { Console.WriteLine("Input string is invalid."); } } } |
That’s all about converting a string to an integer in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)