0

I started c# a month ago and suddenly got a thought that what happens if I don't enter anything for a int value. And I got a error! Would be great if you could help!

    public static void NullChecker()
    {

        Console.Write("Age: ");
        int age = Convert.ToInt16(Console.ReadLine());

        if (age != null)
        {

            if (age >= 16)
            {

                Console.WriteLine("Welcome!");

            }

            else
            {

                Console.WriteLine("You are too young!");
                Console.WriteLine("See you soon!");
            }

        }
        else
        {

            Console.WriteLine("You cant leave it blank!");

        }

    }

I want to know that how do I know if he has entered nothing and redirect him back.Thank you!

  • 1
    Learn about Int32.TryParse and while (or do-while) loop. You could use them to achieve what you want. – Ian Mar 18 '16 at 16:34
  • @Ian i tried Int32.Tryparse and do while (i already know both of them). But returns me an error!"System.FormatException" and i dont see any way how do while can solve this. – Reza Taibur Mar 18 '16 at 16:41
  • Possible duplicate of [How to identify if a string is a number?](http://stackoverflow.com/questions/894263/how-to-identify-if-a-string-is-a-number) – Matthew Verstraete Mar 18 '16 at 17:41

1 Answers1

0

You could use the function Int32.TryParse(). This will return a boolean whether or not the given string is a valid integer.

public static void NullChecker() {

    Console.Write("Age: ");
    String input = Console.ReadLine();

    int age = 0;
    if (Int32.TryParse(input, out age))
    {
        if (age >= 16)
        {

            Console.WriteLine("Welcome!");

        }

        else
        {

            Console.WriteLine("You are too young!");
            Console.WriteLine("See you soon!");
        }

    }
    else
    {

        Console.WriteLine("You cant leave it blank!");

    }

}
Johan
  • 931
  • 9
  • 23
  • @LibertyLocked it's still declared as an 'int' however. 'int' is Int32, it's just being cast back into it. – Dispersia Mar 18 '16 at 17:48