web analytics

How to convert a string to an int in C#?

Options

codeling 1599 - 6654
@2016-01-04 15:13:32

The examples in this topic show some different ways you can convert a string to an int in C#. Such a conversion can be useful when obtaining numerical input from a command line argument, for example.

Convert.ToInt32()

This example calls the ToInt32(String) method to convert an input string to an int . The program catches the two most common exceptions that can be thrown by this method. If the number can be incremented without overflowing the integer storage location, the program adds 1 to the result and prints the output.

    int numVal = -1;
    string input = Console.ReadLine();

    // ToInt32 can throw FormatException or OverflowException.
    try
    {
        numVal = Convert.ToInt32(input);
    }
    catch (FormatException e)
    {
        Console.WriteLine("Input string is not a sequence of digits.");
    }
    catch (OverflowException e)
    {
        Console.WriteLine("The number cannot fit in an Int32.");
    }
    finally
    {
        if (numVal < Int32.MaxValue)
        {
            Console.WriteLine("The new value is {0}", numVal + 1);
        }
        else
        {
            Console.WriteLine("numVal cannot be incremented beyond its current value");
        }
    }

 

Int32.Parse()

Another way of converting a string to an int is through the Parse methods of the System.Int32 struct. The above Convert.ToInt32 method uses Parse internally. If the string is not in a valid format, Parse throws an exception.

try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}

 

@2016-01-04 15:19:51

Int32.TryParse()

You can also use the TryParse methods in the System.Int32 struct to convert a string to an int. As you know, if the string is not in a valid format, Int32.Parse method throws an exception whereas Int32.TryParse method does not throw an exception but returns false.

int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");

string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com