Mohanapriya R Mohanapriya R
Updated date Jul 12, 2024
In this article, we will learn the basics of converting strings to integers in C#. Follow along with a simple program, output, and explanation.

Understanding String-to-Integer Conversion:

In C#, the int.Parse() and int.TryParse() methods are normally used to convert the string to an integer. The int.Parse() method throws an exception if the conversion fails, while int.TryParse() returns a Boolean value, indicating whether the conversion was successful without throwing any exceptions.

using System;

class StringToIntegerConversion
{
    static void Main()
    {
        Console.Write("Enter a number: ");
        string userInput = Console.ReadLine();

        // Using int.Parse()
        try
        {
            int convertedNumber = int.Parse(userInput);
            Console.WriteLine("Using int.Parse(): Converted number: " + convertedNumber);

            // Perform a mathematical operation
            int result = convertedNumber * 2;
            Console.WriteLine("Result after doubling: " + result);
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid input. Please enter a valid integer.");
        }

        // Using int.TryParse()
        if (int.TryParse(userInput, out int parsedNumber))
        {
            Console.WriteLine("Using int.TryParse(): Converted number: " + parsedNumber);

            // Perform a mathematical operation
            int result = parsedNumber * 2;
            Console.WriteLine("Result after doubling: " + result);
        }
        else
        {
            Console.WriteLine("Invalid input. Please enter a valid integer.");
        }
    }
}

Output:

Enter a number: 42
Using int.Parse(): Converted number: 42
Result after doubling: 84
Using int.TryParse(): Converted number: 42
Result after doubling: 84

Comments (0)

There are no comments. Be the first to comment!!!