Back to Home

How to convert string to int in C#

In C#, you can convert a string to an integer using int.Parse() or int.TryParse(). Use Parse() when you're confident the string is valid, and TryParse() when you need to handle invalid input safely.

int.Parse() throws an exception if the conversion fails. int.TryParse() returns a boolean indicating success and outputs the result via an out parameter.

Convert.ToInt32() is another option that handles null values by returning 0, unlike Parse() which throws an exception.

C# Example Code
using System;

// Method 1: int.Parse() - throws exception if invalid
string validNumber = "123";
int number1 = int.Parse(validNumber);
Console.WriteLine($"Parsed: {number1}");

// Method 2: int.TryParse() - safe, no exceptions
string userInput = "456";
if (int.TryParse(userInput, out int number2))
{
    Console.WriteLine($"TryParse succeeded: {number2}");
}
else
{
    Console.WriteLine("TryParse failed");
}

// Method 3: Convert.ToInt32() - handles null
string nullableString = "789";
int number3 = Convert.ToInt32(nullableString);
Console.WriteLine($"Convert: {number3}");

// Handling invalid input with TryParse
string invalidInput = "abc";
if (int.TryParse(invalidInput, out int result))
{
    Console.WriteLine($"Converted: {result}");
}
else
{
    Console.WriteLine($"Cannot convert '{invalidInput}' to int");
}

// Default value pattern
string maybeNumber = "not a number";
int finalNumber = int.TryParse(maybeNumber, out int parsed) ? parsed : 0;
Console.WriteLine($"Final number (with default): {finalNumber}");

Method Comparison

MethodNull inputInvalid inputEmpty stringOverflow
int.Parse()ArgumentNullExceptionFormatExceptionFormatExceptionOverflowException
int.TryParse()Returns falseReturns falseReturns falseReturns false
Convert.ToInt32()Returns 0FormatExceptionFormatExceptionOverflowException

Use int.TryParse() for any user input or data you do not fully control.

Handling Edge Cases

C# Example Code
// Null — TryParse and Convert handle it differently
string? nullInput = null;
Console.WriteLine(int.TryParse(nullInput, out _));  // False (safe)
Console.WriteLine(Convert.ToInt32(nullInput));       // 0 (safe)
// int.Parse(nullInput);                            // ArgumentNullException!

// Empty string
string empty = "";
Console.WriteLine(int.TryParse(empty, out _));       // False (safe)
// int.Parse(empty);                                // FormatException!

// Overflow — number outside int range (-2,147,483,648 to 2,147,483,647)
string tooBig = "99999999999";
Console.WriteLine(int.TryParse(tooBig, out _));      // False (safe)
// int.Parse(tooBig);                               // OverflowException!

// Whitespace — TryParse trims leading/trailing whitespace
Console.WriteLine(int.TryParse("  42  ", out int ws)); // True, ws = 42

Converting to Other Numeric Types

The same Parse / TryParse / Convert pattern works for all numeric types.

C# Example Code
// long — for numbers larger than int.MaxValue (2,147,483,647)
long big = long.Parse("123456789012345");

// double — for decimals
double d = double.Parse("3.14");
bool ok  = double.TryParse("3.14", out double dResult);

// decimal — for financial values (higher precision than double)
decimal price = decimal.Parse("19.99");

// float
float f = float.Parse("3.14");

// Convert.ToX mirrors Convert.ToInt32 behaviour (null → 0, invalid → exception)
long l2 = Convert.ToInt64("123456789012345");

Culture-Aware Parsing

The decimal separator differs by locale (. in en-US, , in de-DE). Use CultureInfo when parsing numbers from external sources.

C# Example Code
using System.Globalization;

// German format: . = thousands separator, , = decimal point
string german = "1.234,56";
decimal amount = decimal.Parse(german, new CultureInfo("de-DE"));
Console.WriteLine(amount); // 1234.56

// Always use InvariantCulture for machine-generated data
string invariant = "1234.56";
decimal inv = decimal.Parse(invariant, CultureInfo.InvariantCulture);
Console.WriteLine(inv); // 1234.56

// NumberStyles for additional control
string hex = "1F4";
int hexValue = int.Parse(hex, NumberStyles.HexNumber);
Console.WriteLine(hexValue); // 500

string withThousands = "1,234";
int formatted = int.Parse(withThousands,
    NumberStyles.Integer | NumberStyles.AllowThousands,
    CultureInfo.InvariantCulture);
Console.WriteLine(formatted); // 1234

Take It Further

The C# Player's Guide book cover

The community's favorite C# guide — teaches every concept you just read about with clarity.

The C# Player's Guide — 5th Edition · RB Whitaker

Get it on Amazon →

As an Amazon Associate I earn from qualifying purchases.