C# How to Convert String to Int with Examples
In C#, you can convert a string to an int using
int.Parse(stringValue) or safely with int.TryParse(stringValue, out int result) to avoid errors.Examples
Input"123"
Output123
Input"0"
Output0
Input"-456"
Output-456
How to Think About It
To convert a string to an int, first check if the string contains only digits (and possibly a sign). Use
int.Parse if you are sure the string is valid, or int.TryParse to safely attempt conversion without crashing if the string is invalid.Algorithm
1
Get the input string.2
Try to convert the string to an integer using a built-in method.3
If conversion succeeds, return the integer value.4
If conversion fails, handle the error or return a default value.Code
csharp
using System; class Program { static void Main() { string str = "123"; int number = int.Parse(str); Console.WriteLine(number); } }
Output
123
Dry Run
Let's trace converting the string "123" to an int using int.Parse.
1
Input string
str = "123"
2
Convert string to int
number = int.Parse("123") results in 123
3
Print result
Console.WriteLine(number) outputs 123
| Step | Value |
|---|---|
| Input string | "123" |
| Converted int | 123 |
| Output | 123 |
Why This Works
Step 1: Using int.Parse
int.Parse converts a valid numeric string directly to an integer but throws an exception if the string is invalid.
Step 2: Using int.TryParse
int.TryParse attempts conversion and returns true or false, preventing exceptions and allowing safe error handling.
Alternative Approaches
int.TryParse
csharp
using System; class Program { static void Main() { string str = "123"; if (int.TryParse(str, out int number)) { Console.WriteLine(number); } else { Console.WriteLine("Invalid number"); } } }
This method is safer because it does not throw an exception if the string is not a valid number.
Convert.ToInt32
csharp
using System; class Program { static void Main() { string str = "123"; int number = Convert.ToInt32(str); Console.WriteLine(number); } }
This method converts the string to int and returns 0 if the string is null, but throws an exception if the string is invalid.
Complexity: O(n) time, O(1) space
Time Complexity
Conversion checks each character once, so it takes linear time relative to the string length.
Space Complexity
Conversion uses constant extra space as it only stores the integer result.
Which Approach is Fastest?
int.Parse and Convert.ToInt32 are similar in speed, but int.TryParse adds a small overhead for safety checks.
| Approach | Time | Space | Best For |
|---|---|---|---|
| int.Parse | O(n) | O(1) | When input is guaranteed valid |
| int.TryParse | O(n) | O(1) | Safe conversion with error handling |
| Convert.ToInt32 | O(n) | O(1) | Handles null but throws on invalid strings |
Use
int.TryParse to safely convert strings without risking exceptions.Trying to convert a non-numeric string with
int.Parse without error handling causes runtime exceptions.