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;

public class StringToInt
{
    public static void Main(string[] args)
    {
        // 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}");
    }
}