Search code examples
c#tryparse

TryParse getting annoying


I am having this really annoying issue (I know this is basic stuff) but when I try use tryparse, I have to enter 2 values before it says integer, I want it to say integer after 1 try. (btw I have to use tryparse) here is an example.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int results = 0;

            Console.WriteLine("how old are you?");
            int.TryParse (Console.ReadLine(), out results);

            if (int.TryParse (Console.ReadLine(), out results))
            {
                Console.WriteLine("integer");                 
            }     
            else
            {
                Console.WriteLine("not an integer");     
            }
            Console.ReadLine();      
        }
    }
}

Solution

  • Get rid of the first redundant call to TryParse e.g.

    class Program
    {
        static void Main(string[] args)
        {
            int results = 0;
    
            Console.WriteLine("how old are you?");
    
            //int.TryParse(Console.ReadLine(), out results); <-- remove this
    
            if (int.TryParse (Console.ReadLine(), out results))
            {
                Console.WriteLine("integer");
            }
            else
            {
                Console.WriteLine("not an integer");
            }
    
            Console.ReadLine();
        }
    }