c# – How to read an int variable if it's an string

If you just want to read a string, try to convert to an integer, and exit the program if it’s not a valid integer, then you’d use int.TryParse, like this:

string input = Console.ReadLine();
if (int.TryParse(input, out x))
{
    // do something with x
}
else
{
    // input was invalid.
}

If you want to continue doing this in a loop until you got invalid input:

bool validInput = true;
while (validInput == true)
{
    string input = Console.ReadLine();
    int x;
    if (int.TryParse(input, out x))
    {
        Console.WriteLine(x);  // output the integer
    }
    else
    {
        Console.WriteLine("Input was not an integer");
        validInput = false;
    }
}

Update

What, exactly, does your test consider “an integer?” Is it just a string that consists only of one or more digits in the set [0-9]? Or does it need to fit within the C# language’s definition of Int32? If the former, then you can use a regular expression to determine if the string is just digits. Otherwise, int.TryParse or int.Parse wrapped in a try ... catch is the way you’ll have to do it.

Leave a Comment