-2

This is a very basic question but how do i only allow numberic values in my if statement? For example if user inputs string as an id it should give an error saying only numeric value allowed.

Console.Write("Please enter your ID: ");
int id = Int32.Parse(Console.ReadLine());
if () // what should I write here?
{
    Console.WriteLine("Only Numeric value are allowed.");
}else{
Console.WriteLine("My ID is {0}", id);}
Habib
  • 219,104
  • 29
  • 407
  • 436
djinc
  • 171
  • 3
  • 14
  • can you use the `char.IsDigit` function perhaps ..? read up on it and try it.. – MethodMan Sep 15 '14 at 15:13
  • @BlueTrin yes, I'd say so too – Adriano Repetti Sep 15 '14 at 15:14
  • you could just not have the if sentence at all. Int32.Parse will throw an exception if the string is not a valid number.. so `try{ int id = Int32.Parse(Console.ReadLine()); Console.WriteLine("My ID is {0}", id);} }catch{ Console.WriteLine("Only Numeric value are allowed."); }` is an option.. – Henrik Mar 27 '18 at 09:17

3 Answers3

6

Use int.TryParse

Console.Write("Please enter your ID: ");
int id;
if (!int.TryParse(Console.ReadLine(), out id)) // what should I write here?
{
    Console.WriteLine("Only Numeric value are allowed.");
}
else
{
    Console.WriteLine("My ID is {0}", id);
}

TryParse group of methods will not raise an exception if parsing is failed, instead they returns a bool indicating success or failure.

Habib
  • 219,104
  • 29
  • 407
  • 436
3

You should do the parse in the if using int.TryParse:

int id;

if (Int32.TryParse(Console.ReadLine(), out id))
{
    // it's an integer!
}
else
{
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

You could use a regular expression such as:

if(Regex.IsMatch("[0-9]") == false)
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Steven Wood
  • 2,675
  • 3
  • 26
  • 51