Quick check if int was submitted

C Sharp - C# (programming language)
Post Reply
dzcadii
Posts: 94
Joined: Sun Mar 01, 2015 4:36 am

Quick check if int was submitted

Post by dzcadii » Sun Mar 01, 2015 10:48 pm

This is just a quick way to check if an int was submitted

I use this to quickly check for an int from a Console.ReadLine() input when I need an int

Code: Select all

public static bool CheckForIntInput(string input)
{
bool isInt = false;
            
int isIntValue;
if (int.TryParse(input, out isIntValue))
{
isInt = true;
}
else
{
isInt = false;
}

return isInt;
}
Usage:

Code: Select all

if(CheckForIntInput(Console.ReadLine()) == false)
{
  //Do something like ask the question again
}
else
{
  //Do something else
}
Or loop Usage:

Code: Select all

string input = Console.ReadLine();
while (CheckForIntInput(input) == false)
{
Console.WriteLine("I will keep showing until I get an int");
input = Console.ReadLine();
}

Post Reply