Search code examples
c#conditional-statementsconsole.writeline

Basic Conditional C# Console App - Not writing anything to Console?


I was just wondering why the console doesn't write my string, but instead shows "Press any key to close".

Would very much appreciate your help!

using System;

namespace oneToTen
{
    public class Conditionals
    {
        static void Main()
        {
        }
        public void NumberPicker()
        {
            Console.Write("Enter a number between 1-10");
            var input = Console.ReadLine();
            var number = Convert.ToInt32(input);
            if (number >= 1 && number <= 10)
            {
                Console.WriteLine("Valid");
            }
            else
            {
                Console.WriteLine("Invalid");
            }
        }
    }
}

Solution

  • Make NumberPicker method static and call it inside Main method

    using System;
    
    namespace oneToTen
    {
       public class Conditionals
       {
          static void Main()
          {
              NumberPicker();
          }
          public static void NumberPicker()
          {
              Console.Write("Enter a number between 1-10");
              var input = Console.ReadLine();
              var number = Convert.ToInt32(input);
              if (number >= 1 && number <= 10)
              {
                  Console.WriteLine("Valid");
              }
              else
              {
                  Console.WriteLine("Invalid");
              }
           }
        }
    }
    

    and you can do everything inside main method in that case you don't need any extra method

    static void Main()
     {
         Console.Write("Enter a number between 1-10");
         var input = Console.ReadLine();
         var number = Convert.ToInt32(input);
         if (number >= 1 && number <= 10)
         {
             Console.WriteLine("Valid");
         }
         else
         {
            Console.WriteLine("Invalid");
         }
     }