Back to Home

How to convert string to int in C#

In C#, you can convert a string to an integer using int.Parse(), int.TryParse(), or Convert.ToInt32(). For user input or data you do not fully control, use int.TryParse() first. Reserve Parse() for trusted input and Convert.ToInt32() when you want null-safe behavior that returns 0 for null.

Quick decision guide

MethodUse whenBehavior on invalid input
int.TryParse()User input, external data, or anything that might be invalidReturns false and leaves the output variable unchanged
int.Parse()You know the input is validThrows FormatException or OverflowException
Convert.ToInt32()You want a null-friendly conversion pathThrows on invalid text, but returns 0 for null
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");

FAQ

Which option should I choose for user input?

Use int.TryParse() so you can show a friendly error message instead of crashing with an exception.

What about whitespace or minus signs?

TryParse() accepts leading and trailing whitespace and handles negative values correctly when the string is valid.

Why does culture matter?

Some cultures use , as the decimal separator, so culture-aware parsing matters more for double, decimal, or float than for plain integer input.

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.