C# String to Int Conversion: Minimal Examples
Here are the primary methods with examples, including pros and cons:
—
#### **1. `int.Parse()`**
“`csharp
string numberString = “123”;
int result = int.Parse(numberString);
“`
**Pros**:
– Simple and concise for *trusted input* (e.g., hardcoded values).
– Throws exceptions for invalid formats (fails fast).
**Cons**:
– Crashes on invalid input (e.g., `”abc”` or `null`).
– Requires try-catch for safety.
—
#### **2. `int.TryParse()`** (Recommended)
“`csharp
string userInput = “456”;
bool success = int.TryParse(userInput, out int result);
// Check if conversion succeeded
if (success)
{
Console.WriteLine($”Converted: {result}”);
}
else
{
Console.WriteLine(“Failed to convert.”);
}
“`
**Pros**:
– **Safe for user input**: Returns `false` instead of throwing exceptions.
– **Efficient**: Avoids exception handling overhead.
– Handles `null` and non-numeric strings gracefully.
**Cons**:
– Slightly more verbose (requires `out` parameter and success check).
—
#### **3. `Convert.ToInt32()`**
“`csharp
string value = “789”;
int result = Convert.ToInt32(value);
“`
**Pros**:
– Handles `null` as `0` (doesn’t throw on `null`).
– Works with other data types (e.g., `bool`, `float`).
**Cons**:
– Throws `FormatException` for non-numeric strings.
– Throws `ArgumentNullException` for `null` in .NET 7+ (breaking change).
– Less intuitive than `int.Parse()` for pure string conversion.
—
### **Key Recommendations**:
1. **Use `int.TryParse()`** for:
– User input (text boxes, APIs, files).
– Scenarios where input validity is uncertain.
2. **Use `int.Parse()`** only when:
– Input is guaranteed valid (e.g., hardcoded strings).
3. **Avoid `Convert.ToInt32()`** for strings:
– Inconsistent null behavior across .NET versions.
– No significant advantages over `int.Parse()`.
—
### **Edge Case Handling**
| **Input** | `int.Parse` | `int.TryParse` | `Convert.ToInt32` (.NET 6+) |
|—————-|——————-|—————-|—————————–|
| `”123″` | ✅ 123 | ✅ 123 | ✅ 123 |
| `” 123 “` | ✅ 123 (trims) | ✅ 123 (trims) | ✅ 123 (trims) |
| `null` | ❌ `ArgumentNullException` | ❌ `false` | ❌ `ArgumentNullException` |
| `””` | ❌ `FormatException` | ❌ `false` | ❌ `FormatException` |
| `”abc”` | ❌ `FormatException` | ❌ `false` | ❌ `FormatException` |
| `2147483648` | ❌ `OverflowException` | ❌ `false` | ❌ `OverflowException` |
—
### **Bonus: Modern C# Pattern Matching**
Combine `int.TryParse()` with pattern matching (C# 7+):
“`csharp
string input = “42”;
if (int.TryParse(input, out int value))
{
Console.WriteLine($”Success! Value: {value}”);
}
else
{
Console.WriteLine($”Failed to parse ‘{input}’.”);
}
“`
This approach minimizes boilerplate and enhances readability.